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));
2
  • 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. Nov 7, 2011 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. Nov 7, 2011 at 22:21

2 Answers 2

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.

2
  • it doesnt append with new File ("Engineer.txt") but i appends with FileOutputStream what is there difference between file and fileoutputstream :S Nov 7, 2011 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. Nov 8, 2011 at 5: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'); 
        
        }
    }

}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.