19

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.

EGHDK
  • 17,818
  • 45
  • 129
  • 204

4 Answers4

18

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());
}
shb
  • 5,957
  • 2
  • 15
  • 32
12

Are you sure the file is created already?

Try adding this:

File file = new File(path);
if (!file.exists()) {
  file.createNewFile();
}
Churk
  • 4,556
  • 5
  • 22
  • 37
  • 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 Mar 26 '12 at 20:48
7

/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.

Tom Meyer
  • 141
  • 3
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).

kurra
  • 13
  • 2