Java filewriter only writing last line to file?

1.9k views Asked by At

What it currently does is reads in the data from a text file and will output them in the specified manner. When I output it to the console then it will display it into the way that is needed but when I try to output it to a text file then it will only write the last line of the loop for some reason. This is the code I have to handle the output for the file:

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

    String gt;
    String gt2;
    int gs1;
    int gs2;
    int total = 0;


    Scanner s = new Scanner(new BufferedReader(
            new FileReader("input.txt"))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");

    while (s.hasNext()) {
        String line = s.nextLine();
        String[] words = line.split("\\s*:\\s*");
        //splits the file at colons

        if(verifyFormat(words)) {
            gt = words[0];       // read the home team
            gt2 = words[1];       // read the away team
            gs1 = Integer.parseInt(words[2]);       //read the home team score
            total = total + gs1;
            gs2 = Integer.parseInt(words[3]);       //read the away team score
            total = total + gs2;
            validresults = validresults + 1;


            File file = new File("out.txt");
            FileOutputStream fos = new FileOutputStream(file);
            PrintStream ps = new PrintStream(fos);
            System.setOut(ps);
            System.out.println(gt + " " +  "[" + gs1 + "]" +  " | " + gt2 + " " + "[" + gs2 + "]");   
            //output the data from the file in the format requested

        }
        else{
            invalidresults = invalidresults + 1;
        }
    }
2

There are 2 answers

2
NoseKnowsAll On BEST ANSWER

Every time you call the constructors for the FileOutputStream and PrintStream, it's like starting over. The objects no longer know that they were supposed to store information about the previous iteration of the loop because they were just constructed. Moving all of these constructors out of your loop and only calling them once will solve your problem. That is

 File file = new File("out.txt");
 FileOutputStream fos = new FileOutputStream(file);
 PrintStream ps = new PrintStream(fos);
 System.setOut(ps);

should be created (once!) before you enter the loop while(s.hasNext()).

0
NickJ On

Each input line, you are creating a new output file and over-writing the old one. This is because the code to create the file is inside the loop!

Move these lines:

File file = new File("out.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);

To just before the while (s.hasNext()) line