Or Ami
Or Ami

Reputation: 91

Android openFileInput causes FileNotFound

I am trying to write / create a file, However no matter how I try it I get a filenotfound exception. I have tried all of this:

FileInputStream is = openFileInput(filename);
File dirs = getFilesDir();
        File f_in = new File(dirs , "score6");
        FileInputStream fs = new FileInputStream(f_in);
Environment.getExternalStorage()

All of those result in FnF I have set my android manifest permission to

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE />    
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

I think the app folder does not exist and because of that it cannot create a new file in that directory, could that be? can an app have no folder even with permission?

What can I do ?

Upvotes: 2

Views: 3461

Answers (2)

svhr
svhr

Reputation: 280

To write a file, you should use FileOutputStream. Using that, if you are opening an stream it will through FileNotFoundException if file is not be present at given location.

To create an empty file using FileOutputStream(assuming from your question as you have shown using FileInputStream)

below statement will create an empty file whether it exists or not:

new FileOutputStream("filename.ext", false).close();

the following statement will create the file if not exists, and will leave if file exists:

new FileOutputStream("filename.ext", true).close();

However, if you want to check before, whether the file exists or not, and perform some operation like create file if not exists, then try this:

File yourFile = new File("filename.ext");
if(!yourFile.exists()) {
    yourFile.createNewFile();
} 
FileOutputStream oFile = new FileOutputStream(yourFile, false);

Upvotes: 2

Diego
Diego

Reputation: 109

You get FileNotFound because you are trying to open input streams, try with:

FileOutputStream is = openFileOutput(filename, MODE_PRIVATE);

You don't need permission to create a file this way. MODE_PRIVATE means that only the application can access that file.

Upvotes: -1

Related Questions