首页 课程 师资 教程 报名

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

  • 2022-12-12 16:13:56
  • 4451次 动力节点

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:	est	est.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:	est	est.txt";
        String word = "试试";
        BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(path,true)));
        out.write(word+"
");
        out.close();
    }
}

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

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交