我得到了錯誤:「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