Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将一行打印到文本文件中_Java - Fatal编程技术网

Java 如何将一行打印到文本文件中

Java 如何将一行打印到文本文件中,java,Java,我想打印出一行来计算写入文本文件的行数,例如: 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 以下是我的

我想打印出一行来计算写入文本文件的行数,例如:

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();
            }
patternstring1=Pattern.compile(“usask.ca”);
patternstring2=Pattern.compile(“128.233”);
模式string3=Pattern.compile(“200”);
Matcher matcher1=string1.Matcher(源地址);
Matcher matcher2=string2.Matcher(源地址);
Matcher matcher3=string3.Matcher(响应代码);
for(int i=0;i

但是上面的代码实际上并没有进行计数,它只是停留在1,并在每个地址之后继续打印出来。我不确定我做错了什么…

您可以尝试使用
扫描仪
并调用
nextLine()
,以及
文件
。链接。这真的很快,像这样的东西可以打印出行数:

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);
}
如果您需要保留代码,请告诉我,我会更新我的答案。

以下是一个示例:

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);
    }