zoukankan      html  css  js  c++  java
  • Java文件操作之文件追加 Chars

     1 import java.io.*;
     2 
     3 public class AppendToFile {
     4     /**
     5      * A方法追加文件:使用RandomAccessFile
     6      */
     7     public static void appendMethodA(String fileName, String content) {
     8         try {
     9             // 打开一个随机访问文件流,按读写方式
    10             RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
    11             // 文件长度,字节数
    12             long fileLength = randomFile.length();
    13             //将写文件指针移到文件尾。
    14             randomFile.seek(fileLength);
    15             randomFile.writeBytes(content);
    16             randomFile.close();
    17         } catch (IOException e) {
    18             e.printStackTrace();
    19         }
    20     }
    21 
    22     /**
    23      * B方法追加文件:使用FileWriter
    24      */
    25     public static void appendMethodB(String fileName, String content) {
    26         try {
    27             //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
    28             FileWriter writer = new FileWriter(fileName, true);
    29             writer.write(content);
    30             writer.close();
    31         } catch (IOException e) {
    32             e.printStackTrace();
    33         }
    34     }
    35 
    36     public static void main(String[] args) {
    37         String fileName = "C:/temp/newTemp.txt";
    38         String content = "new append!";
    39         //按方法A追加文件
    40         AppendToFile.appendMethodA(fileName, content);
    41         AppendToFile.appendMethodA(fileName, "append end. \n");
    42         //显示文件内容
    43         ReadFromFile.readFileByLines(fileName);
    44         //按方法B追加文件
    45         AppendToFile.appendMethodB(fileName, content);
    46         AppendToFile.appendMethodB(fileName, "append end. \n");
    47         //显示文件内容
    48         ReadFromFile.readFileByLines(fileName);
    49     }
    50 }

    下载附件

    原文:http://www.dobug.net/showtopic-625.html

  • 相关阅读:
    python基本数据类型剖析
    常用正则表达式
    python_re模块
    迭代器模式
    状态模式
    备忘录模式
    asp.net 发送邮件
    建造者模式
    抽象工厂模式
    摸板模式与钩子
  • 原文地址:https://www.cnblogs.com/chars/p/3053684.html
Copyright © 2011-2022 走看看