我想要完成的是逐行读取文件并将每行存储到ArrayList中。这应该是一个这么简单的任务,但我一直遇到很多问题。起初,当它被保存回文件时,它正在重复这些行。似乎经常发生的另一个错误是,它跳过了尝试,但没有发现异常?我尝试了几种技术,但没有运气。如果您有任何建议或无论如何可以提供帮助,将不胜感激。谢谢将文件内容添加到ArrayList; Android
当前代码:
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();
}
这似乎适用于将文件保存到数组列表中。但是,在尝试保存文件时,它会遇到异常。所以,第二次尝试块必须有错误。另外,我希望能够用另一个文件做同样的事情。但是,当我尝试使用不同的扫描器变量执行相同的代码时,它强制关闭。 – chRyNaN 2012-07-07 21:14:05
你是从多个线程同时做到这一点?什么是抛出的异常? – 2012-07-07 23:41:31
@ user1478764,您可能得到了路径/文件无效/存在的常见错误。检查路径/文件。 – 2012-07-08 04:25:18