文件写入 – PrintStream追加
我正在尝试将一些信息附加到文本文件中,但该文件只显示写入的最后一个元素。
有许多Engineer
,但它只打印到文件的最后一个被读取的元素。
例如:
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));
我没有看到你正在closures的文件。 我也没有看到你读任何东西。
我假设你想追加到文件,而不是每次覆盖它。 在这种情况下,您需要使用FileOutputStream的append选项,因为这不是默认行为。
PrintStream writetoEngineer = new PrintStream( new FileOutputStream("Engineer.txt", true));
顺便说一句: e.toString() + " "
几乎与e + " "
相同,只是在e为null时不会抛出exception。
由于给出的代码片段的代码不是一个自包含的可编译示例(虽然很简单),但我可以猜测PrintStream是在循环内部创build的,每一次迭代都在Engineer集合中。 这将导致该文件被截断为指示在PrintStream的构造函数javadoc中:
参数:
文件 – 用作此打印stream目的地的文件。 如果文件存在,那么它将被截断为零大小; 否则,将创build一个新文件。 输出将被写入文件并被缓冲。
试试这个例子代码:
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'); } } }