简体   繁体   中英

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

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

Are you sure the file is created already?

Try adding this:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM