Java中向文件写入内容的常见方式

在日常开发中,肯定离不开要和文件打交道,今天就简单罗列一下平时比较常用的创建文件并向文件中写入数据的几种方式,也欢迎大家补充。

1. 使用NIO的Files工具类

java 复制代码
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Collections;

/**
 * @author fu yuan hui
 * @date 2023-10-24 19:39:11 Tuesday
 */
public class FileTest {

    public static void main(String[] args) throws Exception{

        String path = "D:/test/java.txt";
        //Files.createFile(Paths.get(path));

        /**
         * 1.如果文件不存在,则会创建文件
         * 2.这种方式会使后面的内容覆盖前面的内容
         */
        Files.write(Paths.get(path), "hello world!!!".getBytes(StandardCharsets.UTF_8));


        /**
         * 1.如果文件不存在,则会创建文件
         * 2.文件内容追加,
         */
        Files.write(Paths.get(path), "hello world!!!".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);


        /**
         * 文件内容追加. 注意:如果文件存在,则会报错,可以使用 StandardOpenOption.CREATE 或者不写
         */
        Files.write(Paths.get(path), "hello world2222!!!".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW, StandardOpenOption.APPEND);


        /**
         * 1.如果文件不存在,则会创建文件
         * 2.文件内容追加
         * 3.第二个参数是集合,可以实现"换行"追加
         */
        Files.write(Paths.get(path), Collections.singleton("hello world333!"), StandardCharsets.UTF_8, StandardOpenOption.APPEND);
        
        
        //-----------------------------------------------------------------------//
        
       //还可以通过Files.newBufferedWriter来创建文件并写入内容
       
        /**
         * 1.如果文件不存在,会创建文件
         * 2.文件内容会覆盖
         */
        try(BufferedWriter bw = Files.newBufferedWriter(Paths.get(path), StandardCharsets.UTF_8)) {
            bw.write("hello world!!!");
        }


        /**
         * 1.如果文件不存在,会创建文件
         * 2.文件内容会追加
         */
        try(BufferedWriter bw = Files.newBufferedWriter(Paths.get(path), StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
            bw.write("hello world222!!!");
        }
    }
   
}

在实际开发中,如果涉及到文件的创建,我一般是首选Files.createFile或者Files.write这种方式,首先是使用了NIO,性能好,其次是代码简洁。

2.通过commons-io的FileUtils工具类

java 复制代码
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @author fu yuan hui
 * @date 2023-10-24 19:39:11 Tuesday
 */
public class FileTest {

    public static void main(String[] args) throws Exception{

        String path = "D:/test/java3.txt";


        /**
         * 1.如果文件不存在,则创建文件
         * 2.最后一个参数为true,表示追加
         */
        FileUtils.writeStringToFile(new File(path), "hello world999", StandardCharsets.UTF_8, true);
        
    }
}

3.使用BufferedWriter

java 复制代码
package com.efreight.oss.transfer.handler;


import java.io.BufferedWriter;
import java.io.FileWriter;

/**
 * @author fu yuan hui
 * @date 2023-10-24 19:39:11 Tuesday
 */
public class FileTest {

    public static void main(String[] args) throws Exception{

        String path = "D:/test/java3.txt";

        /**
         * 1.如果文件不存在,则创建文件
         * 2.第二个参数为true:表示文件内容是追加
         */
        try(BufferedWriter bf = new BufferedWriter(new FileWriter(path, true))) {
            bf.write("hello world666");
        }

    }
}

4.使用 PrintWriter

java 复制代码
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author fu yuan hui
 * @date 2023-10-24 19:39:11 Tuesday
 */
public class FileTest {

    public static void main(String[] args) throws Exception{

        String path = "D:/test/java3.txt";

        /**
         * 1.如果文件不存在,则创建文件
         * 2.一行一行往文件里面写
         */
        try(PrintWriter printWriter = new PrintWriter(path, StandardCharsets.UTF_8.name())) {
            printWriter.println("hello world111");
            printWriter.println("hello world222");
            printWriter.write("today is very hot");
        }

    }
}

5.使用 RandomAccessFile

java 复制代码
import java.io.RandomAccessFile;

/**
 * @author fu yuan hui
 * @date 2023-10-24 19:39:11 Tuesday
 */
public class FileTest {

    public static void main(String[] args) throws Exception{

        String path = "D:/test/java4.txt";

        /**
         * 1.如果文件不存在,则创建文件
         * 2.可以通过seek方法来实现内容的追加
         */
        for (int i = 0; i < 5; i++) {
            try(RandomAccessFile rf = new RandomAccessFile(path, "rw")) {
                rf.seek(rf.length());
                rf.writeBytes("hello RandomAccessFile: " + i);
            }
        }
    }
}

以上就是我整理的操作文件的常用方法,尤其推荐第一种方式和第二种方式,其他没有罗列的比如: FileOutputStream, FileWriter等等,想必大家也都知道,这里就不再展示了。

相关推荐
abcnull1 小时前
用javaparser做精准测试
java·ast·静态代码分析·精准测试·javaparser
叶小鸡1 小时前
Java 篇-项目实战-苍穹外卖-笔记汇总
java·开发语言·笔记
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题】【Java基础篇】第22题:HashMap 和 HashSet 有哪些区别
java·开发语言·哈希算法·散列表·hash
juniperhan1 小时前
Flink 系列第21篇:Flink SQL 函数与 UDF 全解读:类型推导、开发要点与 Module 扩展
java·大数据·数据仓库·分布式·sql·flink
ID_180079054731 小时前
Python 实现亚马逊商品详情 API 数据准确性校验(极简可用 + JSON 参考)
java·python·json
c++之路2 小时前
C++23概述
java·c++·c++23
专注API从业者3 小时前
Open Claw 京东商品监控选品实战:一键抓取、实时监控、高效选品
java·服务器·数据库
摇滚侠3 小时前
DBeaver 导入数据库 导入 SQL 文件 MySQL 备份恢复
java·数据库·mysql
古城小栈3 小时前
从 cargo-whero 库中,找到提升 rust 的契机
开发语言·后端·rust
keep one's resolveY3 小时前
SpringBoot实现重试机制的四种方案
java·spring boot·后端