Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Write - PrintStream append

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));
like image 657
snnlankrdsm Avatar asked Nov 07 '11 22:11

snnlankrdsm


People also ask

Does PrintStream create a file?

We can use PrintStream class to write a file. It has several methods that let you print any data type values.

How do I append a file with FileOutputStream?

Using FileOutputStream FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter . To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true .

When a file is open for appending Where does write () put new text?

You can use FileWriter to open the file for appending text as opposed to writing text. The difference between them is that when you append data, it will be added at the end of the file. Since FileWriter writes one character at a time, it's better to use BufferedWriter class for efficient writing.

How do you append to file handling in java?

We can append to file in java using following classes. If you are working on text data and the number of write operations is less, use FileWriter and use its constructor with append flag value as true . If the number of write operations is huge, you should use the BufferedWriter.


2 Answers

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.

like image 139
Peter Lawrey Avatar answered Oct 08 '22 16:10

Peter Lawrey


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'); 
        
        }
    }

}
like image 21
yair Avatar answered Oct 08 '22 15:10

yair