java - 打印到文件

标签 java file-processing

我正在尝试将偶数从 input.txt 文件打印到 display.txt 输出文件。每当我将输出发送到输出控制台作为测试时,它都会完美运行。它显示偶数。每当我使用打印流并将其发送到文件时,它只会打印出最后一个偶数。

我研究并询问了我的教授,他说他们不知道出了什么问题。

 Scanner inputfile=new Scanner(new File("input.txt"));
    double sum=0.0;
    int count=0;

    while (inputfile.hasNext())
    {
        if(inputfile.hasNextInt()) 
        {
            int next=inputfile.nextInt();
           int even=(next%2);              
           if(even==0)
           {


           PrintStream output=new PrintStream(new File("display.txt"));
          output.println(next); 
          System.out.println(next); 
           count++;

           }


        }
        else
        {
            inputfile.next();
            continue;

        }

    }

    if(count>0) 
    {

     inputfile.close();
    }
    else
    {
    System.out.println("The file doesn't contain any integers. Exit 
     Program");
    }

display.txt 文件的预期输出均为偶数。文件中仅打印最后一个。

最佳答案

这是因为您在 while 循环的每个循环中实例化 PrintStream,您想要实例化 PrintStream output = new PrintStream(new File("display.txt")); 开始 while 循环之前。

例如:

// More code

PrintStream output = new PrintStream(new File("display.txt"));
while (inputfile.hasNext())
{
    if (inputfile.hasNextInt())
    {
        int next = inputfile.nextInt();
        int even = (next % 2);
        if (even == 0)
        {
            output.println(next);
            System.out.println(next);
            count++;
        }
    }
    else
    {
        inputfile.next();
        continue;
    }
}

// More code

关于java - 打印到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55733808/

相关文章:

Python - 从子目录中找不到的目录文件中读取文件(在那里)

c++ - 写入文件的最后 32 个字符

java - 如何根据学生ID删除特定信息

私有(private)字段的Java垃圾回收

java - 使用 Spring HATEOAS 嵌套嵌入到 HAL 中

java - 如何使用Java查找数组中不同重复值的数量

java - HeaderElement1_1Impl ClassCastException Java 使用 JDK 而不是 saaj-impl

java - Java中的视频-声音-传感器捕获

.net - 计算 XSLT 文件中的记录数

c++ - 文件输入截断第一个字