简体   繁体   中英

How to append using PrintWriter in Java

My Board class has a write method like this

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"));
    }

I used this board to solve Unblock Me game, in my BFSSolution class, after finishing solving, I want to write start and goal board to my output1.txt file

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

start and goal is two instances of Board class. But it did not append at all, neither write anything

How can I append?

I want to use FileOutputStream as a parameter of write method, because I will have many other input2.txt input3.txt with corresponding output2.txt output3.txt , so I did not use the specified path in write method

Please help me

You need to close PrintWriter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM