网站首页 新闻首页 网页设计图形动画软件编程网站开发办公软件操作系统数据库网络技术认证考试范文资料黑客攻防 书籍教程 进入论坛

利用RamdonAccessFile来实现文件的追加!

http://www.diybl.com/ 2007-2-6  网络 点击:  [ 评论 ]
文章搜索:    【点击打包该文章】

RamdonAccessFile 是个很好用的类,功能十分强大,可以利用它的
length()和seek()方法来轻松实现文件的追加,相信我下面这个例子是
很容易看懂的,先写入十行,用length()读出长度(以byte为单位),
在用seek()移动到文件末尾,继续添加,最后显示记录。

import java.io.*;
public class IOStreamDemo {
  public static void main(String[] args) {
    try{
      RandomAccessFile rf1 = new RandomAccessFile("d:\\jeru.txt","rw");
      for (int i = 0; i < 10; i ++ )  {
        rf1.writeBytes("xixi,this is line "+i+"\n");
      }
      rf1.close();
  
      int i = 0;
      String record = new String();
      RandomAccessFile rf2 = new RandomAccessFile("d:\\jeru.txt","rw");
      rf2.seek(rf2.length());
      rf2.writeBytes("lala,append line"+"\n");
      rf2.close();
    
      RandomAccessFile rf3 = new RandomAccessFile("d:\\jeru.txt","r");
      while ((record = rf3.readLine()) != null) {
        i ++;
        System.out.println("Value "+i+":"+record);
      }
      rf3.close();
   }catch(Exception e){}
}
}

欢迎光临DIY部落,点击这里查看更多文章教程   【点击打包该文章】
如果图片或页面不能正常显示请点击这里 站内搜索:   

文章评论

请您留言

 

最新新闻