2015-10-18 75 views
0

我想打印出单独的一行来计算有多少行已被写入到文本文件,例如:如何打印一个单行到一个文本文件

202.32.92.47 | 271 | 200 
ix-or7-27.ix.netcom.com | 205908 | 200 
ram0.huji.ac.il | 271 | 200 
eagle40.sasknet.sk.ca | 1116 | 200 
eagle40.sasknet.sk.ca | 49649 | 200 
cdc8g5.cdc.polimi.it | 461 | 200 
Total number of line: 6 

这里是我的代码部分:

  Pattern string1 = Pattern.compile("usask.ca"); 
      Pattern string2 = Pattern.compile("128.233."); 
      Pattern string3 = Pattern.compile("200"); 
      Matcher matcher1 = string1.matcher(sourceAddress); 
      Matcher matcher2 = string2.matcher(sourceAddress); 
      Matcher matcher3 = string3.matcher(responseCode); 
      for (int i = 0; i < sourceAddress.length(); i++) 
       if ((!matcher1.find() || !matcher2.find()) && matcher3.find()) { 
       bw.write(sourceAddress + " | " + replySizeInBytes + " | " + responseCode); 
       bw.newLine(); 
       bw.write("Total number of line: " + i); 
       bw.newLine(); 
      } 

,但上面的代码实际上没有做计数,它只是停留在1,并保持每个地址后打印出来。我不知道我做错了什么...

回答

1

你可以尝试使用Scanner并呼吁nextLine(),以及FileHere's的链接。这是非常快像这样的打印行数:

public void printLineCount() throws FileNotFoundException { 
    File f = new File("filename.txt"); 
    Scanner s = new Scanner(f); 
    int i = 0; 
    while(s.hasNextLine()) { 
     i++; 
     s.nextLine(); 
    } 
    System.out.println("Total number of line: " + i); 
} 

如果你需要保持你的代码,让我知道,我会更新我的答案。

1

这里是一个例子:

File file = new File("C:"); 
    try{ 
     PrintWriter output = new PrintWriter(file); 
     output.println("ping www.google.cm"); 
     output.close(); 
    }catch(IOException ex){ 
     frame.setVisible(true); 
     frame.setAutoRequestFocus(true); 
    } 
相关问题