Skip to content Skip to sidebar Skip to footer

How Do I Write A Byte Array To A File In Android?

This is my code to create a file. public void writeToFile(byte[] array) { try { String path = '/data/data/lalallalaa.txt'; FileOutputStream stream = ne

Solution 1:

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

It works me perfectly

try {
    if (!file.exists()) {
        file.createNewFile();
    }
    FileOutputStreamfos=newFileOutputStream(file);
    fos.write(bytes);
    fos.close();
} catch (Exception e) {
    Log.e(TAG, e.getMessage());
}

Solution 2:

Are you sure the file is created already?

Try adding this:

Filefile=newFile(path);
if (!file.exists()) {
  file.createNewFile();
}

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.

Solution 4:

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

Post a Comment for "How Do I Write A Byte Array To A File In Android?"