I am building a small software in java to test both functions and PrintWriter method. But When I run it only the last number of the loop is printed. For example on the Odd file only 99 is printed and on the Even file only 100.

I created a couple of system.out.println to test if the loop was working and it seems it is. Does anyone know why it is only printing one line?

   /**
 *
 * @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();
    } 
}
有帮助吗?

解决方案

You are doing this:

  1. open file
  2. write number
  3. close file
  4. start over by going to (1).

This way, you are clearing the previous data of the file. Change your logic to:

  1. open file
  2. write number
  3. goto (2)
  4. when done, close file.

Alternatively, you could choose to write to the file by appending data. But that is not recommended in this scenario. If you would like to try it (only for educational purposes!), you could try to create your PrintWriters like this:

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

其他提示

By default, a PrintWriter overwrites existing files. In your PrintFile method, you create a new PrintWriter object for every write. This means that you override everything you’ve written before in the PrintFile method. Therefore the file only contains the last write. To solve this, use a shared PrintWriter instance.

Please note that by convention, methods, fields and variables in Java start with small letters (numbers(), evenOdd(...), printFile(...), odd, even, file ...). This makes your code more readable for others.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top