我正在开发一个简单的 android 应用程序,我需要在内部存储设备中编写一个文本文件。我知道关于这件事有很多问题(和答案),但我真的无法理解我在以错误的方式做些什么。
这是我在活动中用来编写文件的一段代码:
public void writeAFile(){
String fileName = "myFile.txt";
String textToWrite = "This is some text!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName , Context.MODE_PRIVATE);
outputStream.write(textToWrite.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我真的不明白我在做什么错误。此外,我已经在 Android Studio 和手机的模拟器上尝试 了这个 项目,以了解我在哪里做错了,但即使使用该项目,手机或模拟器上也没有写入文件。
编辑:我知道没有文件写入我的内部存储,因为我尝试在写入文件后使用以下代码读取文件的内容:
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("myFile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
什么都没有显示。
原文由 delca85 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用以下代码将文件写入内部存储:
从 API 19 开始,您必须请求写入存储的权限。
您可以通过将以下代码添加到
AndroidManifest.xml
来添加读写权限:您可以使用以下命令提示用户提供读/写权限:
然后您可以在
onRequestPermissionsResult()
内部调用的活动中处理权限请求的结果。