首页 > 其他 > 详细

FileOutputStream

时间:2014-03-23 09:43:44      阅读:416      评论:0      收藏:0      [点我收藏+]

 三,FileOutputStream写入文件

  文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。请参阅下面的完整的例子。

  代码如下

  package com.yiibai.io;

  import java.io.File;

  import java.io.FileOutputStream;

  import java.io.IOException;

  public class WriteFileExample {

  public static void main(String[] args) {

  FileOutputStream fop = null;

  File file;

  String content = "This is the text content";

  try {

  file = new File("c:/newfile.txt");

  fop = new FileOutputStream(file);

  // if file doesnt exists, then create it

  if (!file.exists()) {

  file.createNewFile();

  }

  // get the content in bytes

  byte[] contentInBytes = content.getBytes();

  fop.write(contentInBytes);

  fop.flush();

  fop.close();

  System.out.println("Done");

  } catch (IOException e) {

  e.printStackTrace();

  } finally {

  try {

  if (fop != null) {

  fop.close();

  }

  } catch (IOException e) {

  e.printStackTrace();

  }

  }

  }

  }

  更新的JDK7例如,www.111cn.net使用新的"尝试资源关闭"的方法来轻松处理文件。

  package com.yiibai.io;

  import java.io.File;

  import java.io.FileOutputStream;

  import java.io.IOException;

  public class WriteFileExample {

  public static void main(String[] args) {

  File file = new File("c:/newfile.txt");

  String content = "This is the text content";

  try (FileOutputStream fop = new FileOutputStream(file)) {

  // if file doesn‘t exists, then create it

  if (!file.exists()) {

  file.createNewFile();

  }

  // get the content in bytes

  byte[] contentInBytes = content.getBytes();

  fop.write(contentInBytes);

  fop.flush();

  fop.close();

  System.out.println("Done");

  } catch (IOException e) {

  e.printStackTrace();

  }

  }

  }

FileOutputStream,布布扣,bubuko.com

FileOutputStream

原文:http://blog.csdn.net/u014131893/article/details/21774469

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!