我想要完成的是逐行读取文件并将每一行存储到 ArrayList 中。这应该是一个如此简单的任务,但我一直遇到很多问题。起初,当它被保存回文件时,它正在重复这些行。另一个似乎经常发生的错误是它跳过了尝试但没有捕获异常?我尝试了几种技术,但没有运气。如果您有任何建议或无论如何可以提供帮助,将不胜感激。谢谢
当前代码:
try{
// command line parameter
FileInputStream fstream = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
fileList.add(strLine);
}
//Close the input stream
in.close();
} catch (Exception e){//Catch exception if any
Toast.makeText(this, "Could Not Open File", Toast.LENGTH_SHORT).show();
}
fileList.add(theContent);
//now to save back to the file
try {
FileWriter writer = new FileWriter(file);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}