【问题标题】:print file writer only writes 1 number打印文件编写器仅写入 1 个数字
【发布时间】:2013-10-29 23:17:28
【问题描述】:

我正在用 java 构建一个小软件来测试功能和 PrintWriter 方法。但是当我运行它时,只打印循环的最后一个数字。例如,奇数文件仅打印 99,偶数文件仅打印 100。

我创建了几个 system.out.println 来测试循环是否正常工作,并且看起来确实如此。有谁知道为什么它只打印一行?

   /**
 *
 * @author bertadevant
 */

import java.io.*;

public class Filewritermethods {

    public static void main(String[] args) throws IOException {

       Numbers();  

   }

   public static void Numbers () throws IOException {

        for (int i =1; i<=100; i++){

            EvenOdd(i);
        }
}

    public static void EvenOdd (int n) throws IOException {

        File Odd = new File ("odd.txt");
        File Even = new File ("even.txt");
        File All = new File ("all.txt");

        PrintWriter all = new PrintWriter (All);

        all.println(n);
        all.close();

        if (n%2==0){

            PrintFile(Even, n);
            System.out.println ("even");
        }

        else {
            PrintFile (Odd, n);
            System.out.println ("odd");
        }

    }

    public static void PrintFile (File filename, int n) throws IOException {

        PrintWriter pw = new PrintWriter (filename);

        if (n!=0) {
            pw.println(n);
            System.out.println (n + " printfile method");
        }

        else {
            System.out.println ("The number is not valid");
        }

        pw.close();
    } 
}

【问题讨论】:

    标签: java user-defined-functions printwriter


    【解决方案1】:

    你正在这样做:

    1. 打开文件
    2. 写号码
    3. 关闭文件
    4. 转到 (1) 重新开始。

    这样,您正在清除文件的先前数据。将您的逻辑更改为:

    1. 打开文件
    2. 写号码
    3. 转到 (2)
    4. 完成后,关闭文件。

    或者,您可以选择通过附加数据来写入文件。但在这种情况下,不推荐。如果您想尝试一下(仅用于教育目的!),您可以尝试像这样创建您的 PrintWriter:

    PrintWriter pw = new PrintWriter(new FileWriter(file, true));
    

    【讨论】:

      【解决方案2】:

      默认情况下,PrintWriter 会覆盖现有文件。在您的PrintFile 方法中,您为每次写入创建一个新的PrintWriter 对象。这意味着您将覆盖您之前在 PrintFile 方法中编写的所有内容。因此该文件仅包含最后一次写入。要解决此问题,请使用共享的 PrintWriter 实例。

      请注意,按照惯例,Java 中的方法、字段和变量以小写字母开头(numbers()evenOdd(...)printFile(...)oddevenfile ...)。这使您的代码对其他人更具可读性。

      【讨论】:

        猜你喜欢
        • 2018-09-18
        • 1970-01-01
        • 1970-01-01
        • 2017-08-18
        • 1970-01-01
        • 1970-01-01
        • 2013-08-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多