我想要完成的是逐行讀取文件並將每行存儲到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