zoukankan      html  css  js  c++  java
  • java文件末尾追加内容的两种方式

    java 开发中,偶尔会遇到在文件末尾对文件内容进行追加,实际上有多种方式可以实现,简单介绍两种:

    一种是通过RandomAccessFile类实现,另一种是通过FileWriter类来实现。

    实现方法很简单,没什么可多说的,直接看代码:

     1     public static void main(String[] args) throws Exception {
     2         File file=new File(filename);
     3         RandomAccessFile raf=new RandomAccessFile(file, "rw");
     4          //将写文件指针移到文件尾。
     5          raf.seek(raf.length());
     6          raf.writeBytes("first test RandomAccessFile append 
    ");
     7          raf.close();
     8          FileWriter writer = new FileWriter(file, true);
     9          writer.write("test RandomAccessFile append 
    ");
    10          writer.close();
    11          raf=new RandomAccessFile(file, "rw");
    12          //将写文件指针移到文件尾。
    13          raf.seek(raf.length());
    14          raf.writeBytes("second test RandomAccessFile append 
    ");
    15          raf.close();
    16     }

    最后查看文件内容:

    first test RandomAccessFile append 
    test RandomAccessFile append 
    second test RandomAccessFile append 

    就这么简单。。。。。

  • 相关阅读:
    python2和python3的区别
    星球大战
    [USACO]高低卡(金)High Card Low Card (Gold)
    学习笔记
    叶子的染色
    大问题
    ...
    考试前...
    [HAOI2010]计数
    [POI2006]OKR-Periods of Words
  • 原文地址:https://www.cnblogs.com/jessezeng/p/5666716.html
Copyright © 2011-2022 走看看