How do I write a byte array to a file in Android?
This is my code for creating the 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 a file to my server just by calling the path String path = "/data/data/lalallalaa.txt";
I am getting a logcat error:
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 the file that it "supposedly" has already been created.
Are you sure the file has already been created?
Try adding this:
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
/ data / data / is a privileged directory in Android. Applications cannot write to or read from this directory.
Instead, you should use context.getFilesDir()
to find a valid filename to use.
I think you better add a tight FileOutputStream function for clear code
It works great.
try {
if (!File.exists()) {
File.createNewFile();
}
FileOutputStream fos = new FileOutputStream(File);
fos.write(bytes);
fos.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
This exception is thrown if either the file does not exist or if you are trying to write to a read-only file. Also try using the fully qualified pathname and see if the same exception occurred (to check if you gave the correct relative path).