Java 在文件末尾追加内容

需求背景:多次向文件中依次写入内容,

需求分析:如何向文件中依次追加内容呢?而且不清空之前的内容。

今天就分享一下基于Java语言,如何在文件末尾追加内容。

import java.io.*;

public class AddContent2TxtLast {
    /**
     * "\\r\\n"用于换行
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // 可以是其它格式的文件
        String pathName = "D:\\img\\test.txt";
        String conent = "\r\n测试,把字符追加到文件末尾";
        addContentPlus(pathName, conent);
        conent = "\r\naddContent2TxtLast";
        addContent2TxtLast(pathName, conent);
        conent = "\r\nmethod2";
        method2(pathName, conent);
    }

    /**
     * 追加文件内容:<p>
     * 判断文件是否存在,不存在则创建<p>
     * 使用FileOutputStream,在构造FileOutputStream时,把第二个参数设为true<p>
     *
     * @param pathName
     * @param conent
     */
    public static void addContentPlus(String pathName, String conent) throws IOException {
        File file = new File(pathName);
        // 判断文件不存在,返回
        if (!judeFileExists(file)) {
            return;
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file, true)));
            out.write(conent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 追加文件:使用FileOutputStream,在构造FileOutputStream时,把第二个参数设为true,表示在文件末尾追加
     *
     * @param pathName
     * @param conent
     * @throws IOException
     */
    public static void addContent2TxtLast(String pathName, String conent) throws IOException {
        FileOutputStream fos = new FileOutputStream(pathName, true);
        fos.write(conent.getBytes());
        fos.flush();
        fos.close();//流要及时关闭
    }

    /**
     * 追加文件:使用FileWriter
     *
     * @param pathName
     * @param content
     */

    public static void method2(String pathName, String content) throws IOException {
        FileWriter writer = null;
        try {
            // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            writer = new FileWriter(pathName, true);
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.flush();
            writer.close();
        }

    }

    // 判断文件是否存在
    public static boolean judeFileExists(File file) {
        if (file.exists()) {
            System.out.println("File exists");
            return Boolean.TRUE;
        } else {
            System.out.println("File not exists, please create it ...");
            return Boolean.FALSE;
        }
    }

}

如果遇到文件目录不存在的场景,请参考《当文件不存在时自动创建文件目录和文件》的解决策略。

posted @ 2021-10-24 19:01  楼兰胡杨  阅读(2038)  评论(1编辑  收藏  举报