File Not Found Exception : Open failed:ENOENT - java

I am new for android, Im downloading image from URL and set in listView. Its working some mobile and not creating file/directory in some mobile.
Its throw error like:
java.io.FileNotFoundException: /storage/emulated/0/.tam/veg.png: open failed: ENOENT (No such file or directory)
I don't know why its throw error like this some mobile. I want to create directory all type of mobile. Please anyone help me.
Here my code:
public class ImageStorage {
public static String saveToSdCard(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory();
File folder = new File(sdcard.getAbsoluteFile(), ".tam");//the dot makes this directory hidden to the user
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), filename) ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
public static File getImage(String imagename) {
File mediaImage = null;
try {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root);
if (!myDir.exists())
return null;
mediaImage = new File(myDir.getPath() + "/.tam/"+imagename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaImage;
}
public static File checkifImageExists(String imagename) {
File file = ImageStorage.getImage("/" + imagename);
if (file.exists()) {
return file;
} else {
return null;
}
}
public static String getImageName(String value){
String getName[] = value.split("/");
return getName[4];
}
}
Below path not in all mobile:
/storage/emulated/0/
Thanks in advance!!

Maybe u should check if there's external storage in the mobile before u use this path
public String getDir(Context context) {
String checkPath = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
checkPath = Environment.getExternalStorageDirectory().getPath();
} else {
checkPath = context.getCacheDir().getPath();
}
return checkPath;
}

Related

Can't unzip file to /storage/emulated/0

I want to unzip file.zip to /storage/emulated/0, do not create a folder. But when destPath = Environment.getExternalStorageDirectory().getPath() + File.separator, it throws FileNotFoundException(Is a Directory), how can I edit my code?
private boolean unZip(String srcPath, String destPath, String password){
File zip = new File(srcPath);
try {
net.lingala.zip4j.ZipFile zipFile = new net.lingala.zip4j.ZipFile(zip);
if (!zipFile.isValidZipFile()) {
throw new ZipException("zipFile is invalid zipFile");
}
if (zipFile.isEncrypted()) {
zipFile.setPassword(password.toCharArray());
}
zipFile.extractAll(destPath);
Log.d("destPath", destPath);
}catch (ZipException e){
e.printStackTrace();
return false;
}
return true;
}

How to restore file from GDrive?

I am making an app which stores its SQLite Database backup on GDrive. I succeeded in signing in and uploading the file in the drive but failed to restore it. Following is the code.
I use SQLiteDatabase to store the fileID so that when it is required while updating and restoring, it can be used. I am looking for a method which will make use of FileID to restore.
Error occurs at file.getDownloadUrl() and file.getContent().
class DriveClassHelper
{
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private static Drive mDriveService;
private String FileID = null;
private static String filePath = "/data/data/com.example.gdrivebackup/databases/Data.db";
DriveClassHelper(Drive mDriveService)
{
DriveClassHelper.mDriveService = mDriveService;
}
// ---------------------------------- TO BackUp on Drive -------------------------------------------
public Task<String> createFile()
{
return Tasks.call(mExecutor, () ->
{
File fileMetaData = new File();
fileMetaData.setName("Backup");
java.io.File file = new java.io.File(filePath);
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("application/x-sqlite-3");
FileContent mediaContent = new FileContent(mimeType, file);
File myFile = null;
FileID = getFileIDFromDatabase();
try {
if (FileID != null) {
Log.i("CALLED : ", FileID);
//mDriveService.files().delete().execute();
myFile = mDriveService.files().update(FileID, fileMetaData, mediaContent).execute();
} else {
myFile = mDriveService.files().create(fileMetaData, mediaContent).execute();
MainActivity.demoSQLite.insertData(myFile.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
if (myFile == null) {
throw new IOException("Null Result when requesting file creation");
}
Log.i("ID:", myFile.getId());
return myFile.getId();
}
);
}
// -------------------------------------------------------------------------------------------------
// ---------------------------------- TO get File ID -------------------------------------------
private static String getFileIDFromDatabase()
{
String FileIDFromMethod = null;
Cursor result = MainActivity.demoSQLite.getData();
if (result.getCount() == 0) {
Log.i("CURSOR :", "NO ENTRY");
return null;
} else {
while (result.moveToNext()) {
FileIDFromMethod = result.getString(0);
}
return FileIDFromMethod;
}
}
// -------------------------------------------------------------------------------------------------
// ---------------------------------- TO Restore -------------------------------------------
public static class Restore extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
String fileId = null;
try
{
fileId = getFileIDFromDatabase();
if (fileId != null)
{
File file = mDriveService.files().get(fileId).execute();
downloadFile(file);
}
else
{
return null;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return fileId;
}
private void downloadFile(File file)
{
InputStream mInput = null;
FileOutputStream mOutput = null;
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) //Error occurs at file.getDownloadUrl()
{
try
{
HttpResponse resp = mDriveService.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
mInput = resp.getContent();
String outFileName = "file://" + Environment.getDataDirectory().getPath() + filePath;
// Log.e("com.example.myapp", "getDatabasePath="+ getDatabasePath(""));
//Log.e("com.example.myapp", "outFileName="+outFileName);
// String outFileName = "../databases/" + "Quickpay.db";
mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
}
catch (IOException e)
{
// An error occurred.
e.printStackTrace();
// return null;
}
finally
{
try
{
//Close the streams
if (mOutput != null)
{
mOutput.close();
}
if (mInput != null)
{
mInput.close();
}
}
catch (IOException e)
{
Log.e("com.example.myapp", "failed to close databases");
}
}
}
else
{
// The file doesn't have any content stored on Drive.
// return null;
Log.e("com.example.myapp", "No content on Drive");
}
}
}
}
The Gradle file is like
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0')
{
exclude group: 'org.apache.httpcomponents'
}
implementation('com.google.api-client:google-api-client-android:1.26.0')
{
exclude group: 'org.apache.httpcomponents'
}
implementation 'com.google.http-client:google-http-client-gson:1.26.0'
As far as i know Download URL is only avalibale in Google drive api v2 and not in V3.
Short lived download URL for the file. This field is only populated for files with content stored in Google Drive; it is not populated for Google Docs or shortcut files.
It was not very stable in my opinion as not all file types would return a download url.
Using Google Drive v3 you should download the file using a stream.
String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
.executeMediaAndDownloadTo(outputStream);
This should work with the restore. Let me know if it doesnt and i will have a look its been a while since i have tried restore.

Java File.renamTo not working

I have made the code which renames all the jpg files in a directory from 1 to n (number of files)..
if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg
But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file
I have wasted one day to resove that issue
Kindly help me
Code:
public class Renaming {
private static String path; // string for storing the path
public static void main(String[] args) {
FileReader fileReader = null; // filereader for opening the file
BufferedReader bufferedReader = null; // buffered reader for buffering the data of file
try{
fileReader = new FileReader("input.txt"); // making the filereader object and paasing the file name
bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
path=bufferedReader.readLine();
fileReader.close();
bufferedReader.close();
}
catch (FileNotFoundException e) { // Exception when file is not found
e.printStackTrace();
}
catch (IOException e) { // IOException
e.printStackTrace();
}
finally {
File directory=new File(path);
File[] files= directory.listFiles(); // Storing the all the files in Array
int file_counter=1;
for(int file_no=0;file_no<files.length;file_no++){
String Extension=getFileExtension(files[file_no]); //getting the filw extension
if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){ // checking that if file is of jpg type then apply renaming // checking thaat if it is file
File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file
new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg")); //Renaming the file
System.out.println(new_file.toString());
file_counter++; // incrementing the file counter
}
}
}
}
private static String getFileExtension(File file) { //utility function for getting the file extension
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1); // gettingf the extension name after .
} catch (Exception e) {
return "";
}
}`
first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS.
This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.
public class App {
private String path = null;
public static int index = 1;
public App(String path){
if (Files.isDirectory(Paths.get( path ))) {
this.path = path;
}
}
public void rename() throws IOException{
if ( this.path != null){
Files.list(Paths.get( this.path ))
.forEach( f ->
{
String fileName = f.getFileName().toString();
String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");
try {
Files.move( f ,Paths.get( this.path + "/" + App.index + "." + extension));
App.index++;
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
}
public static void main(String[] args) throws IOException {
App app = new App("c:/Temp/");
app.rename();
}
}

How to get a XML file from assets via a thread in Android?

Here is my scenario.
I have MainActivity.java in which I am calling the thread like this
private void callXMLParserThread() {
String filePath = "file:///android_asset/weather_conditions.xml";
parserThread = new XMLParserThread(context, filePath);
parserThread.start();
}
and here is my XMLParserThread.java
public class XMLParserThread extends Thread {
Context context;
String fileName;
XMLParser xmlParser;
public XMLParserThread(Context context, String fileName) {
this.context = context;
this.fileName = fileName;
}
#Override
public void run() {
xmlParser = new XMLParser();
String xmlResponse = null;
try {
xmlResponse = xmlParser.getXmlFromFile(context, fileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("xmlResponse", xmlResponse + "");
super.run();
}
}
Notice: In run() method I'm calling the another method getXmlFromFile() resides in XMLParser.java
Now here is my getXmlFromFile() method.
public String getXmlFromFile(Context context, String fileName) throws IOException {
Log.e("fileName", fileName);
InputStream is = null;
try {
is = context.getAssets().open(fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
byte b = (byte)result;
buf.write(b);
result = bis.read();
}
return buf.toString();
}
Problem
When I execute the code it throws the java.io.FileNotFoundException: file:///android_asset/weather_conditions.xml at xml.parser.XMLParser.getXmlFromFile(XMLParser.java:43)
where the line no 43 is is = context.getAssets().open(fileName); in my getXmlFromFile() method
Also, I'm sure the file exists in the assets folder. Where am I making a mistake?
When you define path from assets, write only path of sub-folder of assets.
If you have xml file under:
assets/android_asset/weather_conditions.xml
so file path should be:
String filePath = "android_asset/weather_conditions.xml";
BTW, you have helper in your code:
is = context.getAssets().open(fileName);
context.getAssets() means open assets folder and find out path there.
If I'm not mistaken, you can just say as below without that "file:///..." part.
String filePath = "weather_conditions.xml";

Create Database on SD Card From File

I'm working with Android and I'm trying to use a database I already have. I'd like to put it on the SD card. I have the database file in my project's assets folder. How can I make it on the SD card or external storage of whatever device the app is installed on?
//Step1 : Checked accessiblity on sd card
public boolean doesSDCardAccessible(){
try {
return(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}
//Step2 : create directory on SD Card
//APP_DIR : your PackageName
public void createAndInitAppDir(){
try {
if(doesSDCardAccessible()){
AppDir = new File(Environment.getExternalStorageDirectory(),APP_DIR+"/");
if(!AppDir.exists()){
AppDir.mkdirs();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//Step 3 : Create Database on sdcard
//APP_DIR : your PackageName
//DATABASE_VERSION : give Database Vesrion
//DATABASE_NAME : your Databsename Name
public void initDB()
{
try {
//Using SQLiteHelper Class Created Database
sqliteHelper = new SQLiteHelper(Application.this,AppDir.getAbsolutePath()+"/"+DATABASE_NAME,
null, DATABASE_VERSION);
//OR use following
//Creating db here. or db will be created at runtime whenever writable db is opened.
db = SQLiteDatabase.openOrCreateDatabase(AppDir.getAbsolutePath()+"/"+DATABASE_NAME, null);*/
db= sqliteHelper.getWritableDatabase();
db.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
In reference to this answer, you can find the directory of the SD card in Android 4.0+ by trying both of the following (only one should work per device):
new File("/mnt/external_sd/");
or
new File("/mnt/extSdCard/");
On Android <4.0, you can use
Environment.getExternalStorageDirectory();
You can create your SQLite database there. Additionally, if you can't find it, you can iterate over all directories in /mnt/ (note: the sdcard will always be accessible via /mnt/).
Go throuh this link
OR try following
InputStream myInput;
try {
AssetManager assetManager = getAssets();
myInput = assetManager.open("mydatabase.db");
File directory = new File("/sdcard/some_folder");
if (!directory.exists()) {
directory.mkdirs();
}
OutputStream myOutput = new FileOutputStream(directory
.getPath() + "/DatabaseSample.backup");
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The database is like any other flat file. Just copy it to your SD card.
public boolean backup()
{
File sdcard = Environment.getExternalStorageDirectory();
File data = new File("/data/data/com.mydomain.myappname/databases/");
if (sdcard.canWrite())
{
File input = new File(data, DB_NAME);
File output = new File(sdcard, "android/data/com.mydomain.myappname/databases/");
if(!output.exists())
{
if(output.mkdirs())
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
output.createNewFile();
result = true;
}
else
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
result = true;
}
if(input.exists() && result)
{
FileInputStream source;
FileOutputStream destination;
try
{
source = new FileInputStream(input);
try
{
destination = new FileOutputStream(output);
byte[] buffer = new byte[1024];
int length;
while((length = source.read(buffer)) > 0)
{
destination.write(buffer, 0, length);
}
source.close();
destination.flush();
destination.close();
result = true;
}
catch(Exception e)
{
result = false;
destination = null;
}
}
catch(Exception e)
{
result = false;
source = null;
}
}
else
{
result = false;
}
}
else
{
result = false;
}
}
catch(Exception e)
{
result = false;
}
return result;
}

Categories

Resources