How do I write a byte array to a file in Android?

32,806

Solution 1

Are you sure the file is created already?

Try adding this:

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

Solution 2

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());
}

Solution 3

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

Share:
32,806
EGHDK
Author by

EGHDK

Updated on May 28, 2020

Comments

  • EGHDK
    EGHDK almost 4 years

    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.