当前位置: 移动技术网 > IT编程>开发语言>Java > java文件输出流写文件的几种方法

java文件输出流写文件的几种方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

java文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。

复制代码 代码如下:

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例如,使用新的“尝试资源关闭”的方法来轻松处理文件。
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();
  }
 }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网