【问题标题】:how to print output in a text file如何在文本文件中打印输出
【发布时间】:2014-03-10 22:12:23
【问题描述】:

我正在尝试从文件中读取文本,执行一些操作并将结果输出到不同的文件中,但由于某种原因,它只打印了一行结果。

    Scanner file = new Scanner(new FileInputStream("/.../file.txt"));
    PrintWriter p = new PrintWriter(new FileWriter("/.../output.txt"));

    int count = 0;

    while (file.hasNextLine()) 
    {
        String s = file.nextLine();
        count++; 
        try
        {
            if(s.contains("#AVFC")){
                p.printf("There are %d words on this line ", s.split("\\s").length-1);
                p.println(count);
                p.close();

            }
        }
        catch(Exception ex){ 
            ex.printStackTrace(); 
        } 



    }
    file.close();

这是输出;

There are 4 words on this line 1

但输出应该是:

There are 4 words on this line 1

There are 10 words on this line 13

There are 8 words on this line 16

【问题讨论】:

标签: java printwriter


【解决方案1】:

为什么在while 循环中关闭p?

Scanner file = new Scanner(new FileInputStream("/.../file.txt"));
PrintWriter p = new PrintWriter(new FileWriter("/.../output.txt"));

int count = 0;

while (file.hasNextLine()) 
{
    String s = file.nextLine();
    count++; 
    try
    {
        if(s.contains("#AVFC")){
            p.printf("There are %d words on this line ", s.split("\\s").length-1);
            p.println(count);

        }
    }
    catch(Exception ex){ 
        ex.printStackTrace(); 
    } 



}

p.close();
file.close();

在您的代码中 PrintWriter 在文件中找到第一个匹配项时关闭,其他匹配项不会写入输出文件,因为您之前关闭了文件编写器。

【讨论】:

  • 天哪,真是个愚蠢的错误,哈哈,这是漫长的一天,谢谢先生
【解决方案2】:

不要在循环中关闭您的PrintWriter。 (你仍然需要它。)在循环之后关闭它。

 while(file.hasNextLine())
 { 
    // your code goes here...
 }
 p.close();
 file.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多