文件写入 - PrintStream附加

时间:2011-11-07 22:12:04

标签: java file-io append

我试图将一些信息附加到文本文件中,但该文件只显示最后写入的元素。

有许多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));

2 个答案:

答案 0 :(得分:38)

我看不到您关闭文件的位置。我也没有看到你读任何东西。

我假设你想要附加到文件而不是每次都覆盖它。在这种情况下,您需要使用FileOutputStream的append选项,因为这不是默认行为。

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

BTW:e.toString() + " "e + " "几乎相同,但如果e为null则不会抛出异常。

答案 1 :(得分:3)

由于给定代码片段的代码不是自包含可编译示例(虽然它很简单),但我可以猜测PrintStream是在循环内创建的,每次迭代都在Engineer集合上。这将导致文件被截断,如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'); 

        }
    }

}