PrintWriter create empty file

给你一囗甜甜゛ 提交于 2019-12-01 21:48:12

问题


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, also there is no errors in console.

Here is my code:

System.out.print(sb.toString());
PrintWriter out;
try{
    out = new PrintWriter("filename.txt");
    out.println(sb.toString());
}catch (Exception e) {
    e.printStackTrace();
}

Console output:

[19/3/2014]

Ime in priimek: Matjaz Mav
Naslov: Ppot 6, 1000 Ljubljana 
Telefon: 040 111 222

Registerska št.: LJ 1234
Znamka: Citroen
Model: C4
Letnik: 2005
Opombe: Popravi

Thanks!


回答1:


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().




回答2:


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




回答3:


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




回答4:


   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.



来源:https://stackoverflow.com/questions/23168226/printwriter-create-empty-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!