• java追加写入txt文件


    整理了下网上的资料,数据追加写入txt文件有三种方式,见下面代码:

    方法一:

     1 public void method1() {
     2 FileWriter fw = null;
     3 try {
     4 //如果文件存在,则追加内容;如果文件不存在,则创建文件
     5 File f=new File("E:\dd.txt");
     6 fw = new FileWriter(f, true);
     7 } catch (IOException e) {
     8 e.printStackTrace();
     9 }
    10 PrintWriter pw = new PrintWriter(fw);
    11 pw.println("追加内容");
    12 pw.flush();
    13 try {
    14 fw.flush();
    15 pw.close();
    16 fw.close();
    17 } catch (IOException e) {
    18 e.printStackTrace();
    19 }
    20 }

    方法二:

     1 public static void method2(String file, String conent) {
     2 BufferedWriter out = null;
     3 try {
     4 out = new BufferedWriter(new OutputStreamWriter(
     5 new FileOutputStream(file, true)));
     6 out.write(conent+"
    ");
     7 } catch (Exception e) {
     8 e.printStackTrace();
     9 } finally {
    10 try {
    11 out.close();
    12 } catch (IOException e) {
    13 e.printStackTrace();
    14 }
    15 }
    16 }

    方法三:

     1 public static void method3(String fileName, String content) {
     2 try {
     3 // 打开一个随机访问文件流,按读写方式
     4 RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
     5 // 文件长度,字节数
     6 long fileLength = randomFile.length();
     7 // 将写文件指针移到文件尾。
     8 randomFile.seek(fileLength);
     9 randomFile.writeBytes(content+"
    ");
    10 randomFile.close();
    11 } catch (IOException e) {
    12 e.printStackTrace();
    13 }
    14 }
    15 }
  • 相关阅读:
    小毛驴基本语法
    文本数据IO操作--字符流
    基本IO操作--字节流
    文件指针操作
    文件操作——RandomAccessFile
    Java文件操作——File
    前端修炼-javascript关键字之prototype
    Redux介绍及基本应用
    IOS应用程序生命周期
    EF 只更新部分字段
  • 原文地址:https://www.cnblogs.com/wdpnodecodes/p/8001557.html
Copyright © 2020-2023  润新知