打印出来的结果不是想要的结果,中间夹着乱码~
如何正常打印出结果:
lisi: 24
zhangsan:23
wangwu: 25
代码如下:
- Java code
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(); }}
------解决方案--------------------
以下代码虽然是正确的,但这个东西没有意义,如果保存对象,建议ObjectOutputStream
- Java code
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 字节读写。