在Android中将字节[]数组写入文本文件

在Android中将字节[]数组写入文本文件,android,bytearray,fileoutputstream,Android,Bytearray,Fileoutputstream,这个问题有很多例子。我试过了,但还是不行。 将创建Test.txt文件。但是没有数据写入test.txt文件。 我的代码有什么问题?我在清单文件中有权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 从docopenFileOutput将 Open a private file associated with this Context's application package

这个问题有很多例子。我试过了,但还是不行。 将创建Test.txt文件。但是没有数据写入test.txt文件。 我的代码有什么问题?我在
清单
文件中有权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

从doc
openFileOutput

Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.
那些文件在目录下

data > data > your app id > files
但您的文件不在其外部存储的内部文件夹中

换行

fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
进入


然后从文档中尝试..

openFileOutput
will

Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.
那些文件在目录下

data > data > your app id > files
但您的文件不在其外部存储的内部文件夹中

换行

fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
进入


然后尝试..

因为您正在SD卡中创建文件,但在内部存储中写入文件。尝试如下

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
        "/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
   try {
    file.createNewFile();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
}

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();

原因是,您正在SD卡中创建文件,但正在内部存储器中写入文件。尝试如下

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
        "/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
   try {
    file.createNewFile();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
}

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();

+1个完美答案,我在我的电脑中检查OP的代码,在你的建议之后,它在文件中写得很好。感谢你的详细回答。+1个完美答案,我在我的电脑中检查OP的代码,在你的建议之后,它在文件中写得很好。感谢你的详细回答。应该是fos=新文件输出流(文件);应为fos=新文件输出流(文件);