如何在Android中的文件中写入字节数组?

EGH*_*HDK 7 java android bytearray file logcat

这是我创建文件的代码.

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(); 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

当我尝试通过调用路径将文件发送到我的服务器时 String path = "/data/data/lalallalaa.txt";

我收到此logcat错误消息:

03-26 18:59:37.205: W/System.err(325): java.io.FileNotFoundException: /data/data/lalallalaa.txt
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它找不到已经"假定"创建的文件.

Chu*_*urk 10

你确定文件已经创建了吗?

尝试添加此:

File file = new File(path);
if (!file.exists()) {
  file.createNewFile();
}
Run Code Online (Sandbox Code Playgroud)


The*_*mer 8

我认为你最好添加FileOutputStream的close函数以获得清晰的代码

它非常适合我

try {
    if (!File.exists()) {
        File.createNewFile();
    }
    FileOutputStream fos = new FileOutputStream(File);
    fos.write(bytes);
    fos.close();
} catch (Exception e) {
    Log.e(TAG, e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)


小智 5

/ data/data /是Android中的特权目录.应用无法写入此目录或从中读取.

相反,您应该使用context.getFilesDir()查找要使用的有效文件名.