java printwriter结尾写入_java-PrintWriter追加方法不追加

优化字符流输出:PrintWriter vs BufferedWriter与FileWriter
本文指出在Java中正确处理字符流打印,推荐使用PrintWriter配合BufferedWriter和FileWriter,并介绍了Java 7及以上版本的try-with-resources简化资源管理。讨论了FileOutputStream和原始字节流的区别,以及何时选择OutputStreamWriter。

恕我直言,接受的答案没有考虑到意图是要写字符这一事实。 (我知道这个话题很旧,但是由于在寻找相同的话题时,我偶然发现了这篇文章,然后才找到建议的解决方案,因此我在这里发表。)

从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();

}

}文档中,当您要打印字节时,请使用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();

}

}。

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

此外,从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();

}

}文档中:

除非需要快速输出,否则建议将 任何其write()操作可能为Writer的Writer周围的BufferedWriter 昂贵,例如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();

}

}

另外,从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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值