我得到了错误:“java.io.FileNotFoundException”,用于标准输入和输出文件。目的是为一个文件写入一个字符串,然后再读取它。该文件似乎已被写入,但未打开以供阅读。文件没有被打开的原因吗?在下面的第二部分,阅读文件,是问题所在。提前感谢您的任何建议。使用字符串读取和写入文件
public void test(View view){
//writing part
String filename="file.txt";
String string="Hello world!";
FileOutputStream outputStream;
try {
outputStream=openFileOutput(filename,MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//read part
FileInputStream inputStream;
int length = (int) filename.length();
byte[] bytes=new byte[length];
try {
inputStream=new FileInputStream(filename);
inputStream.read(bytes);
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String data = new String(bytes);
}
如果使用openFileOutput写入文件,则使用openFileInput从中读取。 – greenapps
'int length =(int)filename.length();'。文件名的字符数?与文件大小无关。这是行不通的。 – greenapps
这是错误的感谢。 “长度”已被替换为512.我发现,如果将FileInputStream(filename)替换为openFileInput(filename),代码将起作用。输入输出对似乎是对称的:openFileOutput-openFileInput。麻烦的是,读取值是512字节,而原始字符串是简单的,“你好,世界!”。 – gnoejh