文件写入 - 打印流追加

2022-09-02 11:28:36

我正在尝试将一些信息附加到文本文件中,但该文件仅显示写入的最后一个元素。

有很多 s,但它只打印到文件读取的最后一个元素。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));

答案 1

我看不到您要在哪里关闭文件。我也没有看到你读任何东西。

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

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

BTW:几乎与e为空相同,只是它不会引发异常。e.toString() + " "e + " "


答案 2

由于给定的代码片段不是自包含的可编译示例(虽然它很简单),所以我可以猜测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'); 
        
        }
    }

}