问题
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:
Are you sure the file is created already?
Try adding this:
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
回答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());
}
回答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.
回答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).
来源:https://stackoverflow.com/questions/9878150/how-do-i-write-a-byte-array-to-a-file-in-android