我正在开发一个简单的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的模拟器和我的手机上尝试了这项目,以了解我在哪里做错了什么,但是即使在这个项目中,也没有任何文件是在电话或模拟器上写的。
编辑:我知道没有任何文件被写入到我的内部存储中,因为我尝试用以下代码读取文件的内容:
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();
}
}什么都没有显示出来。
发布于 2022-07-03 23:43:39
要将文件写入内部存储,可以使用以下代码:
val filename = "myfile"
val fileContents = "Hello world!"
context.openFileOutput(filename, Context.MODE_PRIVATE).use {
it.write(fileContents.toByteArray())
}https://stackoverflow.com/questions/44587187
复制相似问题