恕我直言,接受的答案没有考虑到意图是要写字符这一事实。 (我知道这个话题很旧,但是由于在寻找相同的话题时,我偶然发现了这篇文章,然后才找到建议的解决方案,因此我在这里发表。)
从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);
}
优化字符流输出:PrintWriter vs BufferedWriter与FileWriter
本文指出在Java中正确处理字符流打印,推荐使用PrintWriter配合BufferedWriter和FileWriter,并介绍了Java 7及以上版本的try-with-resources简化资源管理。讨论了FileOutputStream和原始字节流的区别,以及何时选择OutputStreamWriter。
3365

被折叠的 条评论
为什么被折叠?



