首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >java文件操作使用buffer_java使用BufferedOutputStream写文件

java文件操作使用buffer_java使用BufferedOutputStream写文件

作者头像
用户7886150
修改2021-04-08 11:05:45
修改2021-04-08 11:05:45
6360
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: Java BufferedOutputStream类

2014-05-19 06:30:01

 阅读( 2229 )

 下面代码演示如何使用BufferedOutputStream类写文件。

 使用BufferedOutputStream类写文件,需要先将字符串转换为字节数组,然后再写入。

 import java.io.BufferedOutputStream;

 import java.io.FileNotFoundException;

 import java.io.FileOutputStream;

 import java.io.IOException;

 /**

 *

 * @author outofmemory.cn

 */

 public class Main {

 /**

 * Prints some data to a file

 */

 public void writeToFile(String filename) {

 BufferedOutputStream bufferedOutput = null;

 try {

 //Construct the BufferedOutputStream object

 bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));

 //Start writing to the output stream

 bufferedOutput.write("Line one".getBytes());

 bufferedOutput.write("\n".getBytes()); //new line, you might want to use \r\n if you're on Windows

 bufferedOutput.write("Line two".getBytes());

 bufferedOutput.write("\n".getBytes());

 //prints the character that has the decimal value of 65

 bufferedOutput.write(65);

 } catch (FileNotFoundException ex) {

 ex.printStackTrace();

 } catch (IOException ex) {

 ex.printStackTrace();

 } finally {

 //Close the BufferedOutputStream

 try {

 if (bufferedOutput != null) {

 bufferedOutput.flush();

 bufferedOutput.close();

 }

 } catch (IOException ex) {

 ex.printStackTrace();

 }

 }

 }

 /**

 * @param args the command line arguments

 */

 public static void main(String[] args) {

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

 }

 }

 分享给朋友:

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

 您想查看更多的信息:

 面试题

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档