PrintWriter create empty file

后端 未结 4 1725
生来不讨喜
生来不讨喜 2021-01-20 22:21

I have StringBuilder sb and I want that string save as *.txt file. Problem is that I get \"filename.txt\" but it is completely empty,

相关标签:
4条回答
  • 2021-01-20 22:58

    Either create your PrintWriter with this constructor, changing the first argument to an OutputStream:

    out = new PrintWriter(new FileOutputStream("filename.txt"), true);
    

    to turn on auto flushing, or, just close the writer once you're done writing to it with out.close().

    0 讨论(0)
  • 2021-01-20 23:02

    You should use out.close() statement in this program.

    0 讨论(0)
  • 2021-01-20 23:06

    out.close (); is missing. You have to put it in to close the session.

    0 讨论(0)
  • 2021-01-20 23:08
       PrintWriter out;
       try{
           out = new PrintWriter("filename.txt");
           out.println(sb.toString());
           //add the below lines
           out.flush();
           out.close();
       }catch (Exception e) {
           e.printStackTrace();
       }
    

    Another way is to have a PrintWriter with autoFlush on. That can be achieved by

      out = new PrintWriter(new FileOutputStream("filename.txt"), true);
    

    If you do only out.close() that would also solve the problem at hand as that would internally flush the content written in its internal buffer.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题