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等等,想必大家也都知道,这里就不再展示了。

相关推荐
.生产的驴10 分钟前
SpringBoot 消息队列RabbitMQ 消费者确认机制 失败重试机制
java·spring boot·分布式·后端·rabbitmq·java-rabbitmq
Code哈哈笑27 分钟前
【C++ 学习】多态的基础和原理(10)
java·c++·学习
chushiyunen32 分钟前
redisController工具类
java
A_cot38 分钟前
Redis 的三个并发问题及解决方案(面试题)
java·开发语言·数据库·redis·mybatis
刘某某.44 分钟前
使用OpenFeign在不同微服务之间传递用户信息时失败
java·微服务·架构
alden_ygq44 分钟前
GCP容器镜像仓库使用
java·开发语言
七折困1 小时前
列表、数组排序总结:Collections.sort()、list.sort()、list.stream().sorted()、Arrays.sort()
java·集合·数组·排序
苹果酱05671 小时前
一文读懂SpringCLoud
java·开发语言·spring boot·后端·中间件
掐指一算乀缺钱2 小时前
SpringBoot 数据库表结构文档生成
java·数据库·spring boot·后端·spring
晚睡早起₍˄·͈༝·͈˄*₎◞ ̑̑2 小时前
苍穹外卖学习笔记(七)
java·windows·笔记·学习·mybatis