天天看點

案例 1-7: 利用 RandomAccessFile 向檔案追加内容

import java.io.*;

public class AppendFile {

 public static void main(String[] args) {

  String toAppend = args[0];

  try {

   int i = 0;

   String record = new String();

   String toCn = null;

   // 進行中文問題

   toCn = new String(toAppend.getBytes("GBK"), "ISO8859_1");

   RandomAccessFile rf = new RandomAccessFile("c://aaa.txt", "rw");

   rf.seek(rf.length());

   rf.writeBytes(toCn + "/n");

   rf.close();

   RandomAccessFile rf2 = new RandomAccessFile("c:/aaa.txt", "r");

   String outCn = null;

   while ((record = rf2.readLine()) != null) {

    i++;

    // 進行中文問題

    outCn = new String(record.getBytes("ISO8859_1"), "GBK");

    System.out.println("Line " + i + ":" + outCn);

   }

   rf2.close();

  } catch (Exception e) {

   e.printStackTrace();

  }

 }

}