专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 基础入门学习:Java把内容写入txt文件

基础入门学习:Java把内容写入txt文件

更新时间:2022-12-12 16:13:56 来源:赢咖4 浏览3755次

Java写入数据进txt文件,需求:多条数据追加进文件,且需要处理中文编码问题。

以下代码只能处理向文件添加数据的功能,但是会覆盖掉之前的数据

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Write {
    public static void main(String[] args) throws IOException {
        String word = "hahahahhahahahhah";
        FileOutputStream fileOutputStream = null;
        File file = new File("F:\test\test.txt");
        if(!file.exists()){
            file.createNewFile();
        }
        fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(word.getBytes("gbk"));
        fileOutputStream.flush();
        fileOutputStream.close();

    }
}

正确实例

public class Test{
    public static void main(String[] args) throws IOException {
        String path = "F:\test\test.txt";
        String word = "试试";
        BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(path,true)));
        out.write(word+"
");
        out.close();
    }
}

以上就是赢咖4小编介绍的"基础入门学习:Java把内容写入txt文件",希望对大家有帮助,如有疑问,请在线咨询,有专业老师随时为您务。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>