可以使用 Java 中的 FileWriter 类来将字符输出到现有的文本文件中。下面是一个示例代码:

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

public class Main {
    public static void main(String[] args) {
        String filePath = 'path/to/existing_file.txt';
        String content = 'Hello, World!';

        try {
            FileWriter fileWriter = new FileWriter(filePath, true); // 第二个参数为true表示追加内容
            fileWriter.write(content);
            fileWriter.close();
            System.out.println('内容已成功写入文件。');
        } catch (IOException e) {
            System.out.println('写入文件时出现错误。');
            e.printStackTrace();
        }
    }
}

在上面的代码中,首先指定了要写入的文件路径 (filePath) 和要写入的内容 (content)。然后,通过创建一个 FileWriter 对象,并传入文件路径和一个布尔值 true 来表示追加内容,打开要写入的文件。接下来,使用 write 方法将内容写入文件。最后,通过调用 close 方法关闭文件。如果在写入文件时出现错误,将会捕获 IOException 并打印错误堆栈信息。

Java 向现有文本文件写入字符:完整指南和代码示例

原文地址: https://www.cveoy.top/t/topic/jGXp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录