日期:2014-05-20 浏览次数:20647 次
import java.io.*; public class RandomFileTest { public static void main(String []args) throws Exception { Employee emp1=new Employee("zhangsan",23); Employee emp2=new Employee("lisi",24); Employee emp3=new Employee("wangwu",25); RandomAccessFile raf1=new RandomAccessFile("employee.txt","rw"); raf1.write(emp1.name.getBytes()); raf1.write(emp1.age); raf1.write(emp2.name.getBytes()); raf1.write(emp2.age); raf1.write(emp3.name.getBytes()); raf1.write(emp3.age); raf1.close(); byte []buf=new byte[8]; int len=0; String strName=null; RandomAccessFile raf2=new RandomAccessFile("employee.txt","r"); //打印第二行 raf2.skipBytes(9);// 跳转到九个字节后 len=raf2.read(buf);//读取到字节数组中,并计算多少个字符串。 strName=new String(buf,0,len);//写入 System.out.println(strName+":"+raf2.read()); //打印第一行 raf2.seek(0);//跳转到开始 len=raf2.read(buf); strName=new String(buf,0,len); System.out.println(strName+":"+raf2.read()); //打印第三行 raf2.skipBytes(9);//跳转到九个字节后 len=raf2.read(buf); strName=new String(buf,0,len); System.out.println(strName+":"+raf2.read()); raf2.close(); } }
public class RandomFileTest { public static void main(String []args) throws Exception { Employee emp1=new Employee("zhangsan",23); Employee emp2=new Employee("lisi",24); Employee emp3=new Employee("wangwu",25); RandomAccessFile raf1=new RandomAccessFile("employee.txt","rw"); raf1.write(emp1.name.getBytes()); raf1.write(emp1.age); raf1.write(emp2.name.getBytes()); raf1.write(emp2.age); raf1.write(emp3.name.getBytes()); raf1.write(emp3.age); raf1.close(); byte []buf=new byte[8]; int len=0; String strName=null; RandomAccessFile raf2=new RandomAccessFile("employee.txt","r"); //打印第二行 raf2.skipBytes(9);// 跳转到九个字节后 len=raf2.read(buf,0,4);//读取到字节数组中,并计算多少个字符串。 strName=new String(buf,0,len);//写入 System.out.println(strName+":"+raf2.read()); //打印第一行 raf2.seek(0);//跳转到开始 len=raf2.read(buf); strName=new String(buf,0,len); System.out.println(strName+":"+raf2.read()); //打印第三行 raf2.skipBytes(5);//跳转到九个字节后 len=raf2.read(buf,0,6); strName=new String(buf,0,len); System.out.println(strName+":"+raf2.read()); raf2.close(); } }
------解决方案--------------------
你不就是要一个那么简单的结果么,有必要弄那么多复杂的代码啊?!干吗不用简单的代码。
------解决方案--------------------
在读取时 注意 一次读入的字节数。
------解决方案--------------------
此文的意义仅在于练习RandomAccessFile 字节读写。