温馨提示×

java怎么往txt文件添加内容

小亿
96
2024-05-31 18:03:09
栏目: 编程语言

要往txt文件添加内容,可以使用Java中的FileWriter类来实现。下面是一个简单的示例代码:

import java.io.FileWriter;
import java.io.IOException;

public class AppendToFile {
    public static void main(String[] args) {
        String fileName = "test.txt";
        String content = "This is the content to be added to the file.";

        try {
            FileWriter fw = new FileWriter(fileName, true); // 第二个参数为true表示以追加模式打开文件
            fw.write(content);
            fw.close();
            System.out.println("Content added to the file successfully.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

运行该代码后,会将content的内容添加到test.txt文件末尾。记得要处理可能出现的IOException异常。

0