2016-09-29 61 views
-3

后,下面的代码不会打印最后一部分的文本文件如下:为什么。我

.I 1 
some text 
.I 2 
some text 
.I 3 
some text 
........ 

下面的代码使用StringBuilder的线追加。下面的代码拆分上面的文本文件,并找到它时创建多个文件。我

但问题是当我运行的代码,它不创建文件的最后.I 它有1400。 。所以应该有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(); 
      } 
    } 
} 

回答

0

要追加到StringBuilder在你的循环的底部,你用的FileWriter写完后,这意味着追加到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 **** 
    } 
} 

我建议你简化逻辑和代码:

  • 甚至没有使用StringBuilder,因为没有优势,这是在当前形势下使用。只需创建一个字符串。
  • 一定要提取并使用while循环内的所有文本,然后再编写文本。
0

当您遇到以“.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(); 
    } 
} 
+0

是的,我明白了这一点 –