My app can't open internal storage file

715 Views Asked by At

Android app: Newly created files on internal storage appear in the listing of files, but trying to open the files creates an exception 'No such file or directory'. (Android 8.0, tested on several devices.)

//create a file in internal storage
FileOutputStream output = null;
output = openFileOutput("xxxyyy.txt", Context.MODE_PRIVATE);
String str = "Just any string";
byte[] bytes = str.getBytes();
output.write(bytes, 0, bytes.length);
output.close();

//list the files
String lst[] = fileList();
for (int i = 0; i < lst.length; i++)
{ Log.v("MM" , "INTERNAL FILES: "+lst[i]); }
//system reply: INTERNAL FILES: xxxyyy.txt, ......


//check if file exists and try to open it for reading
File file = new File("xxxyyy.txt");
Log.v("XX" , "TEST: file exists? " + file.exists());
//system reply: TEST: file exists? false

//try to open it for reading
FileInputStream input = null;
try {
    input = new FileInputStream("xxxyyy.txt");
} catch (IOException e) {
   Log.v("XX" , "TEST: " + e.getMessage());
}
//system reply: TEST: xxxyyy.txt (No such file or directory)

Many variations have been tried. Any suggestion greatly appreciated!

1

There are 1 best solutions below

0
rosghub On BEST ANSWER

If you need to access a file created with openFileOutput, you need to specify the correct directory when creating the File object, in this case:

File file = new File(getFilesDir(), "xxxyyy.txt");