19

I am trying to append some information into a text file, but the file only shows the last element written.

There are many Engineers, but it prints to the file only the last element which is read.

For example:

Engineer e = new Engineer(firstName,surName,weeklySal);
PrintStream writetoEngineer = new PrintStream(new File ("Engineer.txt"));

//This is not append. Only print. Overwrites the file on each item.
writetoEngineer.append(e.toString() + " "  + e.calculateMontly(weeklySal));
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
snnlankrdsm
  • 1,401
  • 5
  • 19
  • 29
  • 1
    That's not what `PrintStream.append` means; it doesn't claim to append to a file (it doesn't even know it's dealing with a file). The documentation for a method you're using is usually relevant. – Mark Peters Nov 07 '11 at 22:18
  • Also note that it seems like you're writing all of the Engineers within one instance of your program. If that's the case, you might not even need file append, but could rather move your `PrintStream` creation outside of the loop that iterates over your engineers. – Mark Peters Nov 07 '11 at 22:21

2 Answers2

54

I don't see where you are closing the file. I don't see you reading anything either.

I assume you want to append to the file instead of overwriting it each time. In that case you need to use the append option of FileOutputStream as this is not the default behaviour.

PrintStream writetoEngineer = new PrintStream(
     new FileOutputStream("Engineer.txt", true)); 

BTW: e.toString() + " " is almost the same as e + " " except it doesn't throw an exception if e is null.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • it doesnt append with new File ("Engineer.txt") but i appends with FileOutputStream what is there difference between file and fileoutputstream :S – snnlankrdsm Nov 07 '11 at 22:49
  • 2
    @Mert: `File` doesn't have a constructor where you can specify to append like the `FileOutputStream` constructor that Peter used. Obviously if you specify `false` in the latter, it won't append. What is the difference between `File` and `FileOutputStream`? They are completely disjoint. When you pass a `File` to a `PrintStream` it will create a `FileOutputStream` under the hood, but in non-append mode. It's just there for convenience. Similarly you could pass a `File` into `FileOutputStream` but it also takes a String for convenience. – Mark Peters Nov 08 '11 at 05:00
3

Since the code given code snippet isn't a Self Contained Compilable Example (it is Simple though), I can just guess that the PrintStream is created inside the loop, per each iteration over the Engineer collection. That would cause the file to be truncated as indicate in PrintStream's constructor javadoc:

Parameters:

file - The file to use as the destination of this print stream. If the file exists, then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

try this example code:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;


public class PrintEngineers {

    public static class Engineer {
    
        private final String firstName;
        private final String surName;
        private final int weeklySal;
    
        public Engineer(String firstName, String surName, int weeklySal) {
            super();
            this.firstName = firstName;
            this.surName = surName;
            this.weeklySal = weeklySal;
        }

        public int calculateMonthly() {
            return weeklySal * 4; // approximately
        }
    
        @Override
        public String toString() {
            return firstName + " " + surName;
        }
    }

    /**
     * @param args
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException {
    
        Engineer e1 = new Engineer("first1", "sur1", 100);
        Engineer e2 = new Engineer("first2", "sur2", 200);
        Engineer e3 = new Engineer("first3", "sur3", 300);

        List<Engineer> engineers = new ArrayList<>(3);
        engineers.add(e1);
        engineers.add(e2);
        engineers.add(e3);

        // instanciate PrintStream here, before the loop starts
        PrintStream writetoEngineer = new PrintStream(new File("Engineer.txt"));
        for (Engineer engineer : engineers) {
            // new PrintStream(...) here truncates the file (see javadoc)               //This is not append.Only print.Refresh file on each item 
            writetoEngineer.append(engineer.toString()).append(' ')
                        .append("" + engineer.calculateMonthly()).append('\n'); 
        
        }
    }

}
Community
  • 1
  • 1
yair
  • 8,945
  • 4
  • 31
  • 50