[英]why the following code does not print the last part after .I
文本文件如下:
.I 1
some text
.I 2
some text
.I 3
some text
........
以下代碼使用 stringbuilder 附加行。 下面的代碼分割上面的文本文件並在找到 .I 時創建多個文件
但問題是當我運行代碼時,它不會為最后一個創建文件。我在文件中有 1400 .I。 所以應該有1400個文本文件。 但它會產生 1399 個文本文件。 有什么問題 ? 我找不到問題所在。
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String inputFile="C:\\logs\\test.txt";
BufferedReader br = new BufferedReader(new FileReader(new File(inputFile)));
String line=null;
StringBuilder sb = new StringBuilder();
int count=1;
try {
while((line = br.readLine()) != null){
if(line.startsWith(".I")){
if(sb.length()!=0){
File file = new File("C:\\logs\\DOC_ID_"+count+".txt");
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(sb.toString());
writer.close();
sb.delete(0, sb.length());
count++;
}
continue;
}
sb.append(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
br.close();
}
}
}
在使用 FileWriter 寫入之后,您將附加到循環底部的 StringBuilder,這意味着附加到 StringBuilder 的最后一行將不會寫入文件:
try {
while((line = br.readLine()) != null){
if(line.startsWith(".I")){
if(sb.length()!=0){
File file = new File("C:\\logs\\DOC_ID_"+count+".txt");
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(sb.toString());
writer.close();
sb.delete(0, sb.length());
count++;
}
continue;
}
sb.append(line); // here ****
}
}
建議你簡化一下邏輯和代碼:
當您遇到以“.I”開頭的行時,您想關閉現有文件(如果有)並啟動一個新文件。 其他所有內容都會附加到當前打開的文件中。 確保最后檢查是否有打開的文件並關閉它。
public static void main(String[] args) throws IOException {
String inputFile="C:\\logs\\test.txt";
BufferedReader br = new BufferedReader(new FileReader(new File(inputFile)));
String line=null;
int count=1;
try {
PrintWriter writer = null;
while((line = br.readLine()) != null){
if(line.startsWith(".I")){
if(writer != null) writer.close();
writer = new PrintWriter(file, "UTF-8");
}
if(writer != null){
writer.println(line);
}
}
if(writer != null){
writer.close;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
br.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.