java怎么往txt文件添加内容

   2024-10-13 9230
核心提示:要往txt文件添加内容,可以使用Java中的FileWriter类来实现。下面是一个简单的示例代码:import java.io.FileWriter;import java

要往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异常。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号