Android Log File IO - File/Directory not found error - android

I am trying to create a file for logging, but when I create the file I am getting a File or Directory not found error. I'm not sure what I am doing wrong. This is the code that makes the file:
File directory = new File(Environment.DIRECTORY_DOCUMENTS,"test");
directory.mkdirs();
File file = new File(directory, fileName.trim()+".txt");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
The error is being thrown by createNewFile(). What is causing this error?

You should use getExternalPublicDirectory(Environment.DIRECTORY_DOCUMENTS) to retrieve the normal Documents directory.
directory.mkdirs();
Dont call mkdirs blindly. But only if the directory not exists. And then check the return value as it might fail to create one.

Create a Document directory first.
File docDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
if (!docDir.exists()) {
if(docDir.mkdirs()) {
File directory = new File(docDir,"test");
} else {
// Unable to create document directory. check Run time permissions
}
}

The issue was caused by the app not requesting permissions at runtime as greenapps suggested.

Related

Android check existence of file in android internal storage

I put some .mp4 file in a folder in my android device internal storage. And then I play this file from my application. It plays well if exists otherwise app crushed.
So before play file I want to check its existence.
I tried below code but no luck.
File file = new File("file:///storage/emulated/0/tutorial/1a1cbfc4-18cb-4637-8405-01bf9bebeda3.mp4");
if (file.exists()) {
LogUtil.printLogMessage(VideoListActivity.class.getName(), "video File", "file exist");
} else {
LogUtil.printLogMessage(VideoListActivity.class.getName(), "video File", "file not exist");
}
i am sure the file is exist in the folder named tutorial in my internal storage.
Use file.isFile() for file & file.isDirectory() for directory,
file.exists() tries to access the file which causes it to crash if the file doesn't exist, file.isFile() uses linux stat, which only returns the information about the file without trying to access it.
Please make proper file name, Replace with File myDirectory = new File(Environment.getExternalStorageDirectory(), dirName);
public Boolean checkFile(){
File file = new File("/storage/emulated/0/tutorial/1a1cbfc4-18cb-4637-8405-01bf9bebeda3.mp4");
if (file.exists()) {
return true;
} else {
return false;
}
}
Use checkfile True/False flag before video play.
Try this
File file = new File(path);
if (!file.isFile()) {
}else{
}

Can I see the file created in Android Tablet by file.createNewFile()?

I created a file by file.createNewFile() command in "data/data/com.android.bonvoyage" folder to test file creation in the internal storage of my android tablet.
I found that the file should be visible when I have root account, but I want to find a way
to see the file created without root permission.
I don't care where the file is created, just want to see and test it on actual tablet.
Can I do that?
The process was successful by
File file = new File("data/data/com.android.bonvoyage/myfile.txt");
boolean tf = false;
if (!file.exists()) {
try {
tf = file.createNewFile();
} catch (IOException ioe) {
Toast.makeText(this, ioe.toString(), 5000).show();
//ioe.printStackTrace();
} finally {
Toast.makeText(this, "File Created? " + Boolean.toString(tf), Toast.LENGTH_SHORT).show();
}
}
With root explorer or any file explorer that supports root you could browse to: data/data/com.android.bonvoyage/myfile.txt and look whether its there or not?
Write the file to the sdcard and then you can see it with the file browser without root permissions.
Use the following code (taking from the android guide) to open a file in the pictures folder for example:
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
The full guide can be found here:
http://developer.android.com/training/basics/data-storage/files.html#WriteExternalStorage

Error when call write()

I have error in line:
workbook.write();
When I try debug, i see massage: "Source not found."
How it fix?
private void exportExcel() throws IOException, WriteException{
File file = new File(Environment.getExternalStorageDirectory() + "/backup.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
workbook.createSheet("worksheet", 0);
workbook.write();
workbook.close();
}
Thanks in advance
WTF my code above begin to work!!!
When I started, I using default jexcelapi. Afterwards I begin using alternative jexcelapi, but it also not work.
When I try your code with little changes - it work! Your code:
private void exportExcel() throws WriteException, IOException{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard + "/myFolder");
//make them in case they're not there
dir.mkdirs();
//create a standard java.io.File object for the Workbook to use
File wbfile = new File(dir, "backup.xls");
WritableWorkbook workbook = null;
try{
workbook = Workbook.createWorkbook(wbfile);
workbook.createSheet("worksheet", 0);
workbook.write();
workbook.close();
} catch (IOException ex) {
Log.e("Workbook Test", "Could not create " + wbfile.getPath(), ex);
}
}
But when I try my code above, it also work.
Maybe Eclipse not instantly update using library?
Thank you very much!
P.S. Excuse me for my bad english.
Your code does not check that the external storage directory is actually available. You need to call getExternalStorageState and check the return value against the various MEDIA_* values defined in Environment. If the directory is not available, that may cause the problem.
The problem also may be that you are trying to write to the root of the external storage directory. From the docs:
Applications should not directly use this top-level directory, in order to avoid polluting the user's root namespace. Any files that are private to the application should be placed in a directory returned by Context.getExternalFilesDir, which the system will take care of deleting if the application is uninstalled.
EDIT
Try this code:
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard + "/myFolder");
//make them in case they're not there
dir.mkdirs();
//create a standard java.io.File object for the Workbook to use
File wbfile = new File(dir, "backup.xls");
try{
WritableWorkbook workbook = Workbook.createWorkbook(wbfile);
workbook.createSheet("worksheet", 0);
workbook.write();
workbook.close();
} catch (IOException ex) {
Log.e("Workbook Test", "Could not create " + wbfile.getPath(), ex);
}
return wb;
That should tell you more about what's going on.
EDIT 2
After a little more research, I found another possible issue: JExcelApi uses a lot of resources when it is creating a file. One solution is to use a temp file. Add the following code:
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setUseTemporaryFileDuringWrite(true);
and inside the try block, change the line that creates the workbook:
WritableWorkbook workbook = Workbook.createWorkbook(wbfile, wbSettings);

check that given file is present on this path or not in Android Filesystem?

How can we check the given file is present in Android Filesystem or not without using File inputstream.because I only want to check the existence of the file on the given path.
File myFile = new File("/path/to/file");
if (myFile.isFile()) {
...
}
If you have created a file using openFileOutput method then this works
File mFile = new File(getBaseContext().getFilesDir(),FileName);
if (mFile.exists() )
{
//File is Exits.
}
else
{
//File is not Exits.
}
hope this helps

Android: Creating file using createNewFile() method

As described in android documentation, to create a new file which will be situated in the application's directory there is the method in Context class: openFileOutput().
But where will be the file situated if I use simple createNewFile() method from File class.?
CreateNewFile() is used like this:
File file = new File("data/data/your package name/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
So you will tell the file where it should be created. Remember that you can only create new files on your package. That is "data/data/your package name/".
Somehow createNewFile() was not able to create the complete file path here on my devices.
try {
if (!futurePhotoFile.exists()) {
new File(futurePhotoFile.getParent()).mkdirs();
futurePhotoFile.createNewFile();
}
} catch (IOException e) {
Log.e("", "Could not create file.", e);
Crouton.showText(TaskDetailsActivity.this,
R.string.msgErrorNoSdCardAvailable, Style.ALERT);
return;
}
it will be stored in the current directory to which your classPath is pointing to
Depends on the path you pass to the File constructor. If the parent directory exists, and if you have the permission to write to it, of course.
Documentation of createNewFile() method says:
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
Therefore we don't need to check existence of a file manually:
val dir = context.filesDir.absolutePath + "/someFolder/"
val logFile = File(dir + "log.txt")
try {
File(dir).mkdirs() // make sure to call mkdirs() when creating new directory
logFile.createNewFile()
} catch (e: Exception) {
e.printStackTrace()
}

Categories

Resources