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

相关推荐
东风破_4 小时前
danci 项目(三):从 JSON 数据到 AI Coding,真实项目里的数据清洗、Prompt 和工程规范
前端·后端·node.js
y = xⁿ4 小时前
DeepSeek Harness 学习日记:关于Agent接口,工具调用的底层实现
android·java·学习
东风破_4 小时前
danci 项目(一):从需求到架构,一个单词学习系统为什么会这样设计
前端·后端·node.js
侧耳倾听1115 小时前
jwt使用简介
java·jwt
顶点多余5 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
AI人工智能+电脑小能手5 小时前
大白话说Java设计模式-46-责任链模式(业务实战篇)
java·设计模式·责任链模式·风控校验·servlet filter·spring interceptor·链式处理
jay神6 小时前
【计算机毕业设计】基于SpringBoot的程序教学辅助系统
java·前端·vue.js·spring boot·后端·毕业设计·课程设计
2601_962066496 小时前
【Sql Server】Update中的From语句,以及常见更新操作方式
android·java·数据库
yaoxin5211237 小时前
507. Java 反射 - 在 BeanFactory 中实现依赖注入
java·开发语言
OPEN-F7 小时前
C++模板教程:变参模板、折叠表达式与SFINAE
java·开发语言·c++