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

时间:2023-11-08 16:17:30 

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,文件
0
投稿

猜你喜欢

  • mybatis-generator生成文件覆盖问题的解决

    2023-03-11 15:35:01
  • 深入了解Spring中的@Autowired和@Resource注解

    2021-09-19 06:57:20
  • C#获取web.config配置文件内容的方法

    2023-12-24 12:22:27
  • kotlin gson反序列化默认值失效深入讲解

    2022-04-07 15:28:59
  • c# 实现RSA非对称加密算法

    2021-10-15 10:54:06
  • MyBatis Log 插件无法显示SQL语句的原因解析

    2023-11-24 23:42:55
  • 初学者Android studio安装图文详解

    2022-08-06 07:22:12
  • 详解Vue响应式的部分实现

    2022-12-21 23:25:53
  • Maven配置文件pom.xml详解

    2022-07-03 02:26:43
  • Java标识接口的使用方法

    2021-12-24 02:54:14
  • Flutter开发技巧ListView去除水波纹方法示例

    2021-12-27 14:15:24
  • Struts2配置文件中使用通配符的方法(三种形式)

    2022-08-21 01:53:40
  • Java生成含字母和数字的6位随机字符串

    2023-04-02 02:28:58
  • JavaGUI常用三种布局使用介绍

    2023-05-19 08:01:06
  • Struts2学习笔记(5)-参数传递方法

    2023-08-30 13:03:21
  • SpringBoot自定义加载yml实现方式,附源码解读

    2022-01-22 22:39:40
  • 一篇文章带你入门Java修饰符

    2021-12-25 12:46:01
  • C#窗体实现酒店管理系统

    2023-05-23 18:58:47
  • 如何基于FTP4J实现FTPS连接过程解析

    2022-09-19 21:51:35
  • mybatis关系映射之一对多和多对一

    2021-08-01 21:14:26
  • asp之家 软件编程 m.aspxhome.com