trying to get length of file which from local storage. File exists 100% (because I even tried to create it straight before getting the length (and checked it exists). Code is as simple as:
try {
InputStream is = new FileInputStream("errorlog2.txt");
// Get the size of the file
long length = file.length();
// Close the input stream and return length
is.close();
return length;
}
catch (IOException e) {
Log.w(BaseHelper.TAG_MAIN_ACTIVITY, "bad stuff: ", e);
return 0;
in 100% cases it throws an exception. What might be the problem? What`s correct way to get length of local storage files?
thanks a lot!
UPDATE (full code) – file exists and readable, but no length 🙁
//creating file
String someFileName = "errlogtest.log";
try {
FileOutputStream fOut = openFileOutput(someFileName, Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("dsgaadfg0df9g0sdf90sg9058349 sdf");
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
//reading file
try {
FileInputStream fileToOpen = openFileInput(someFileName);
byte[] readerByte = new byte[fileToOpen.available()];
while (fileToOpen.read(readerByte) != -1) {
}
String fileContents = new String(readerByte);
fileContents.toString();
// next line works fine
Toast.makeText(getApplicationContext(), "FILE CONTENTS: " + fileContents, Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Log.w("Reading file", "Unable to open file");
} catch (IOException e) {
Log.w("Reading file", "Error reading file");
}
// trying to get length
// simply not working:
File file = new File(someFileName);
long length2 = file.length();
Toast.makeText(getApplicationContext(), "FILE LENGTH:" + length2, Toast.LENGTH_LONG).show();
// shows zero and filenotfoundexception: /errlogtest.log
try {
RandomAccessFile raffile = new RandomAccessFile(new File(someFileName), "r");
long length = raffile.length();
Toast.makeText(getApplicationContext(), "FILE LENGTH:" + length, Toast.LENGTH_LONG).show();
catch (IOException e) {
Log.w("Reading file", "Error reading file", e);
}
help please
Depending on where you are creating the file then you’ll need to provide a full path and not just a file name.
For example, if the file is being created using
Context.openFileOutput(...)then you would use something like…