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

相关推荐
二月夜6 小时前
剖析Java正则表达式回溯问题
java·正则表达式
xuhaoyu_cpp_java7 小时前
项目学习(三)分页查询
java·经验分享·笔记·学习
程序员二叉7 小时前
【Java】集合面试全套精讲|HashMap/ArrayList高频考点完整版
java·面试·哈希算法
cfm_29148 小时前
JVM GC垃圾回收初步了解
java·开发语言·jvm
心之伊始8 小时前
LangChain4j RAG 实战:Java 后端如何把本地文档接入 Embedding 检索链路
java·架构·源码分析·csdn
许彰午8 小时前
17_synchronized关键字深度解析
java·开发语言
阿正的梦工坊9 小时前
【Rust】02-变量、不可变性与基础类型
开发语言·后端·rust
Xzh042310 小时前
AI Agent 学习路线(Java 后端方向)
java·人工智能·学习
我叫黑大帅10 小时前
通过php 中的Route:: 的写法了解什么是静态类调用
后端·面试·php
JS菌10 小时前
AI Agent 沙箱双层防护体系:从权限过滤到内核隔离的完整实现
前端·人工智能·后端