PrintWriter附加方法不附加

snn*_*dsm 45 java printwriter

以下方法仅写出我添加的最新项目,它不会附加到以前的条目.我究竟做错了什么?

public void addNew() {
    try {
        PrintWriter pw = new PrintWriter(new File("persons.txt"));
        int id = Integer.parseInt(jTextField.getText());
        String name = jTextField1.getText();
        String surname = jTextField2.getText();
        Person p = new Person(id,name,surname);
        pw.append(p.toString());
        pw.append("sdf");
        pw.close();
    } catch (FileNotFoundException e) {...}
}
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 89

PrintWriter调用方法的事实append()并不意味着它改变了打开文件的模式.

您还需要在追加模式下打开文件:

PrintWriter pw = new PrintWriter(new FileOutputStream(
    new File("persons.txt"), 
    true /* append = true */)); 
Run Code Online (Sandbox Code Playgroud)

另请注意,该文件将以系统默认编码写入.它并不总是需要并且可能导致互操作性问题,您可能希望明确指定文件编码.


Ste*_*han 17

PrintWriter pw = new PrintWriter(new FileOutputStream(new File("persons.txt"),true));
Run Code Online (Sandbox Code Playgroud)

true是追加旗帜.见文档.


Sum*_*ngh 12

以附加模式打开文件,如下面的代码:

 PrintWriter pw = new PrintWriter(new FileOutputStream(new File("persons.txt"), true)); 
Run Code Online (Sandbox Code Playgroud)


mar*_*cra 9

恕我直言,接受的答案并不考虑意图是写字符的事实.(我知道这个主题已经过时了,但是因为在搜索同一个主题时我偶然发现了这个帖子,然后才找到建议的解决方案,我在这里发帖.)

FileOutputStream文档中,您可以FileOutputStream在要打印字节时使用.

FileOutputStream用于写入原始字节流,例如图像数据.要编写字符流,请考虑使用FileWriter.

此外,来自BufferedWriter文档:

除非需要提示输出,否则建议将BufferedWriter包装在其write()操作可能代价高昂的任何Writer周围,例如FileWriters和OutputStreamWriters.

最后,答案如下(如其他StackOverFlow帖子中所述):

PrintWriter out = null;
try {
    out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
    out.println("the text");
}catch (IOException e) {
    System.err.println(e);
}finally{
    if(out != null){
        out.close();
    }
} 
Run Code Online (Sandbox Code Playgroud)

此外,从Java 7开始,您可以使用try-with-resources语句.关闭声明的资源不需要finally块,因为它是自动处理的,并且也不那么详细:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
}catch (IOException e) {
    System.err.println(e);
}
Run Code Online (Sandbox Code Playgroud)