java文件写入printstream append

beq87vna  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(394)

我试图将一些信息附加到文本文件中,但该文件只显示最后写入的元素。
有很多 Engineer s、 但它只将最后一个读取的元素打印到文件中。
例如:

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));
6mzjoqzu

6mzjoqzu1#

我看不出你在哪里关闭文件。我也没看到你在读什么。
我假设您希望附加到文件中,而不是每次都覆盖它。在这种情况下,您需要使用fileoutputstream的append选项,因为这不是默认行为。

PrintStream writetoEngineer = new PrintStream(
     new FileOutputStream("Engineer.txt", true));

顺便说一句: e.toString() + " " 几乎和 e + " " 如果e为null,它不会抛出异常。

5ktev3wc

5ktev3wc2#

由于给定的代码片段不是一个自包含的可编译示例(尽管很简单),我只能猜测printstream是在循环内创建的,每次迭代都是在engineer集合中创建的。这将导致文件被截断,如printstream的构造函数javadoc所示:
参数:
文件-要用作此打印流目标的文件。如果文件存在,那么它将被截断为零大小;否则,将创建一个新文件。输出将写入文件并进行缓冲。
请尝试以下示例代码:

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

        }
    }

}

相关问题