由于给定的代码片段不是自包含的可编译示例(虽然它很简单),所以我可以猜测PrintStream是在循环内创建的,每次迭代工程师集合。这将导致文件被截断,如PrintStream的构造函数javadoc所示:
参数:
file - 要用作此打印流的目标的文件。如果文件存在,则它将被截断为零大小;否则,将创建一个新文件。输出将写入文件并进行缓冲。
试试这个示例代码:
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');
}
}
}