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

相关推荐
老张聊数据集成3 分钟前
数据分析师如何构建自己的底层逻辑?
后端·数据分析
咕噜分发企业签名APP加固彭于晏14 分钟前
市面上有多少智能体平台
前端·后端
掘金一周1 小时前
我开源了一款 Canvas “瑞士军刀”,十几种“特效与工具”开箱即用 | 掘金一周 8.14
前端·人工智能·后端
缉毒英雄祁同伟1 小时前
企业级WEB应用服务器TOMCAT
java·前端·tomcat
村姑飞来了1 小时前
Spring 扩展:动态使某个 @Import 方式导入的 @Configuration 类失效
后端
开心就好20251 小时前
前端性能优化移动端网页滚动卡顿与掉帧问题实战
后端
语落心生1 小时前
如何利用Paimon做流量定时检查? --- 试试标签表
后端
paopaokaka_luck1 小时前
校园快递小程序(腾讯地图API、二维码识别、Echarts图形化分析)
vue.js·spring boot·后端·小程序·uni-app
用户298698530141 小时前
C# 使用Spire.XLS快速生成多表格Excel文件
后端