源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-01-04 18:42 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java文件输出流写文件的几种方法
java文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。
[u]复制代码[/u] 代码如下:
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();   }  } }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部