Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <blockquote> <p>Parameters:</p> <p>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.</p> </blockquote> <p>try this example code:</p> <pre><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&lt;Engineer&gt; engineers = new ArrayList&lt;&gt;(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'); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload