温馨提示×

java writeline如何追加内容

小樊
92
2024-07-26 15:49:10
栏目: 编程语言

要在Java中追加内容到文件中,您可以使用FileWriter类的构造函数中的第二个参数来指定是否追加内容。将参数设置为true以打开文件以进行追加。下面是一个示例代码:

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

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

        try {
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
            System.out.println("Content successfully appended to file.");
        } catch (IOException e) {
            System.err.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

在这个示例中,我们使用FileWriter类打开名为"output.txt"的文件以进行追加,并向文件中写入内容。如果文件不存在,它将被创建。如果您要在新行中追加内容,可以在content字符串的末尾添加换行符(\n)。

0