【问题标题】:How to append using PrintWriter in Java如何在 Java 中使用 PrintWriter 追加
【发布时间】:2015-06-12 21:33:39
【问题描述】:

我的Board 类有一个像这样的write 方法

public void write(FileOutputStream fo) throws IOException
    {
        PrintWriter out=new PrintWriter(fo,true);
        for (int i = 0; i < size; i++) {
            String formatted="%3d";
            for (int j=0;j<size;j++)
            {
                out.append(String.format(formatted,arr[i][j]));
            }
            out.append(System.getProperty("line.separator"));
        }
        out.append(System.getProperty("line.separator"));
    }

我用这个板解决了Unblock Me游戏,在我的BFSSolution课上,解决完后,我想将startgoal板写入我的output1.txt文件

fo=new FileOutputStream("output\\output1.txt");
start.write(fo);
goal.write(fo);

startgoalBoard 类的两个实例。但它根本没有追加,也没有写任何东西

如何追加?

我想用FileOutputStream作为write方法的参数,因为我会有很多其他的input2.txtinput3.txt和对应的output2.txtoutput3.txt,所以我没有使用@中的指定路径987654338@方法

请帮帮我

【问题讨论】:

    标签: java file append fileoutputstream printwriter


    【解决方案1】:

    您需要关闭 PrintWriter

     public void write(FileOutputStream fo) throws IOException{
        PrintWriter out=new PrintWriter(fo,true);
        .....
        out.close();// To save need to close PrintWriter.
    }
    

    【讨论】:

    • 如果我这样做,在完成start.write(fo)之后,方法goal.write(fo)不会追加
    • 比您需要更改代码的设计,以便您可以重用 write 方法。但是要写入文件,您必须关闭资源。
    猜你喜欢
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多