专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java文件输出流写文件的几种方法

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

更新时间:2020-08-24 16:58:56 来源:动力节点 浏览1971次

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();
  }
 }
}

以上就是动力节点java培训机构的小编针对“Java文件输出流写文件的几种方法”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>