java I/O:文件的随机存取

import java.io.*;

 

public class randomAccess {

 /**
  * @param args
  */
 String Filename;
 public randomAccess(String Filename)
 {this.Filename=Filename;}
 
 public void writeEmployee(Employee e,int n)throws Exception
 {
  RandomAccessFile ra=new RandomAccessFile(Filename,"rw");
  ra.seek(n*20);
  for(int i=0;i<8;i++)
  ra.writeChar(e.name[i]);
  ra.writeInt(e.age);
  ra.close();
 }
 
 public void readEmployee(int n)throws Exception
 {
  char[] buf=new char[8];
  RandomAccessFile ra=new RandomAccessFile(Filename,"r");
  ra.seek(n*20);
  for(int i=0;i<8;i++)
  buf[i]=ra.readChar();
  System.out.print("name: ");
  System.out.println(buf);
  System.out.println("age: "+ra.readInt());
  ra.close();
 }


 public static void main(String[] args) throws Exception{
  // TODO Auto-generated method stub
  File f=new File(args[0]);
  if(f.exists())
   {f.delete();
   f.createNewFile();
   }
  else
   f.createNewFile();
     randomAccess r=new randomAccess(args[0]);
     r.writeEmployee(new Employee("fhgujghdf",30), 0);
     r.writeEmployee(new Employee("yjngilmsme",23), 1);
     r.writeEmployee(new Employee("rf",12), 2);
     r.writeEmployee(new Employee("4grw",30), 3);
     for(int i=0;i<4;i++)
     r.readEmployee(i);
 }

}

 

   class Employee
   {
    char name[]={'/u0000','/u0000','/u0000','/u0000','/u0000','/u0000','/u0000','/u0000'};
    int age;
    public Employee(String name,int age)throws Exception
    {
     if(name.toCharArray().length>8)
     System.arraycopy(name.toCharArray(), 0, this.name, 0, 8);
     else
      System.arraycopy(name.toCharArray(), 0, this.name, 0, name.toCharArray().length);
     this.age=age;
    }
   }


 /*学习心得
1.RandomAccessFile类
RandomAccessFile(String filename,String mode)    创建从中读取和向其中写入(可选)的随机存取文件流,该文件具有指定名称。
void seek(long pos)   设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。
void wirtechar(int v)    按双字节值将 char 写入该文件,先写高字节
void readchar()       从此文件读取一个 Unicode 字符

 

2.String类
char[] toCharArray()    以字符数组形式返回字符串

 

3.System.arraycopy(char[] s,long spos,char[] d,long dpos,long length)  用作字符数组之间的复制
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值