appendfile.java

来自「实例精华」· Java 代码 · 共 45 行

JAVA
45
字号

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 rf1
		= new RandomAccessFile("e:\\toAppend.txt","rw");
      //length()方法得到的字符长度,包括每一行中的回车符,回车符为一个字节
      rf1.seek(rf1.length());
      //此处为了显示一下读取到的文件的长度,用字节来表示。一个汉字为2个字节
      System.out.println(rf1.length());
      rf1.writeBytes(toCn+"\n");
      rf1.close();

      RandomAccessFile rf2 = new RandomAccessFile("e:\\toAppend.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();
   }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?