0
我需要將文本行寫入文件,然後逐行讀取它們。 所以我用這些代碼寫入文件:將文本文件的行讀取到字符串數組中
String string = "Hello world55555555555!" + "\r\n";
FileOutputStream outputStream;
try {
outputStream = getActivity().openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
它似乎正常工作。但是當我閱讀時會出錯!我試圖通過這些代碼讀取它:
FileInputStream inputStream = null;
BufferedReader reader;
String[] text = new String[0];
List <String> words = new ArrayList <String>();
String line;
try {
inputStream = getActivity().openFileInput(filename);
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = reader.readLine()) != null) {
words.add(line);
}
text = new String[words.size()];
text = words.toArray(text);
} catch (IOException e) {
//You'll need to add proper error handling here
}
tv.setText(text[0]);
Toast.makeText(getActivity(), text[1],
Toast.LENGTH_SHORT).show();
}
有什麼意見!請!
任何時候你「出現錯誤」 [請告訴我們錯誤信息](https://secure.phabricator.com/book/phabflavor/article/please_please_please/)。 –