21

This is my code to create a file.

public void writeToFile(byte[] array) 
{ 
    try 
    { 
        String path = "/data/data/lalallalaa.txt"; 
        FileOutputStream stream = new FileOutputStream(path); 
        stream.write(array); 
    } catch (FileNotFoundException e1) 
    { 
        e1.printStackTrace(); 
    } 
} 

When I try to send my file to my server by just calling the path String path = "/data/data/lalallalaa.txt";

I get this logcat error message:

03-26 18:59:37.205: W/System.err(325): java.io.FileNotFoundException: /data/data/lalallalaa.txt

I don't understand why it can't find a file that is "supposedly" created already.

1
  • 2
    don't forget to close the stream afterwards Commented Mar 26, 2012 at 19:08

4 Answers 4

21

I think you'd better add close function of FileOutputStream for clear code

It works me perfectly

try {
    if (!file.exists()) {
        file.createNewFile();
    }
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(bytes);
    fos.close();
} catch (Exception e) {
    Log.e(TAG, e.getMessage());
}
Sign up to request clarification or add additional context in comments.

Comments

13

Are you sure the file is created already?

Try adding this:

File file = new File(path);
if (!file.exists()) {
  file.createNewFile();
}

2 Comments

Yes, that was correct. I was not actually creating a new file. Did not know about that method and didn't know that it was necessary. Thanks
@EGHDK The docs implicitly say that the file will be created: "If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown."
9

/data/data/ is a privileged directory in Android. Apps can't write to this directory or read from it.

Instead, you should use context.getFilesDir() to find a valid filename to use.

Comments

0

This exception is thrown if either the file does not exist or if you are trying to write to a file that is read-only. Also try using full path name and see if the same exception occurs (to check if you gave the correct relative path).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.