java bufferedwrite_java使用BufferedWriter写文件

2015-09-30 06:30:02

阅读( 1927 )

当要写文本文件时最好使用Writer类,而不是直接写OutputStream;因为Writer类就是为写文本而设计的。

使用BufferedWriter写入文本时不用讲文本转换成字节数组。在下面的示例代码中我们向文件中写入两行文本。

import java.io.BufferedWriter;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.IOException;

/**

*

* @author outofmemory.cn

*/

public class Main {

/**

* Prints some data to a file using a BufferedWriter

*/

public void writeToFile(String filename) {

BufferedWriter bufferedWriter = null;

try {

//Construct the BufferedWriter object

bufferedWriter = new BufferedWriter(new FileWriter(filename));

//Start writing to the output stream

bufferedWriter.write("Writing line one to file");

bufferedWriter.newLine();

bufferedWriter.write("Writing line two to file");

} catch (FileNotFoundException ex) {

ex.printStackTrace();

} catch (IOException ex) {

ex.printStackTrace();

} finally {

//Close the BufferedWriter

try {

if (bufferedWriter != null) {

bufferedWriter.flush();

bufferedWriter.close();

}

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

new Main().writeToFile("myFile.txt");

}

}

执行上述代码后文件中的文本如下:

Writing line one to file

Writing line two to file

注意使用BufferedWriter一定要在finally中flush()并close().

分享给朋友:

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息:

面试题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值