爲了格式化正確,我需要處理一個大型文本文件(大約600 MB),將格式化輸出寫入新的文本文件。問題在於將內容寫入新文件的時間大約爲6.2 MB。下面是代碼:Java - 無法完成寫入文本文件
/* Analysis of the text in fileName to see if the lines are in the correct format
* (Theme\tDate\tTitle\tDescription). If there are lines that are in the incorrect format,
* the method corrects them.
*/
public static void cleanTextFile(String fileName, String destFile) throws IOException {
OutputStreamWriter writer = null;
BufferedReader reader = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(destFile), "UTF8");
} catch (IOException e) {
System.out.println("Could not open or create the file " + destFile);
}
try {
reader = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("The file " + fileName + " doesn't exist in the folder.");
}
String line;
String[] splitLine;
StringBuilder stringBuilder = new StringBuilder("");
while ((line = reader.readLine()) != null) {
splitLine = line.split("\t");
stringBuilder.append(line);
/* If the String array resulting of the split operation doesn't have size 4,
* then it means that there are elements of the news item missing in the line
*/
while (splitLine.length != 4) {
line = reader.readLine();
stringBuilder.append(line);
splitLine = stringBuilder.toString().split("\t");
}
stringBuilder.append("\n");
writer.write(stringBuilder.toString());
stringBuilder = new StringBuilder("");
writer.flush();
}
writer.close();
reader.close();
}
我已經找了答案,但問題通常涉及到的事實,作家沒有被關閉或不存在flush()
方法。因此,我在考慮問題出在BufferedReader中。我錯過了什麼?
你嘗試使用正確的沖洗..? – OmniOwl
我第一次嘗試使用刷新一定次數(準確的說是500次),希望避免在週期的每一次迭代中沖洗,但它不起作用。什麼是使用flush的正確方法? – Judas
你能否提供至少一些來自輸入文件(有600 MB的文件)的記錄? – Jagger