public static void main(String[] args) throws IOException {
WriteMethod();
ReadMethod();
}
public static void WriteMethod() throws IOException{
RandomAccessFile ra = new RandomAccessFile("d:\\ran.txt","rw");
ra.write("王五".getBytes());
ra.writeInt(22);
ra.close();
}
public static void ReadMethod() throws IOException{
RandomAccessFile ra = new RandomAccessFile("d:\\ran.txt","r");
byte[] buf = new byte[1024];
int len = ra.read(buf);
String name = new String(buf,0,len);
int age = ra.readInt();
System.out.println(name);
System.out.println(age);
ra.close();
}
}
复制代码
报的是Exception in thread "main" java.io.EOFException 这个错误。看着和视频里没太大区别啊??作者: 谢达 时间: 2013-4-6 19:00
RandomAccessFile ra = new RandomAccessFile("d:\\ran.txt","r");
byte[] buf = new byte[1024]; //字节数组的大小问题,你把数组大小变为4就可以了
//把文件里数据全部读进字节数组,此处数组长度太长,它会把文件所以内容读出来指针已经到达文件末尾,所以后面readInt()时会显示Unknown Source,
int len = ra.read(buf);
String name = new String(buf,0,len);
int age = ra.readInt();
System.out.println(name);
System.out.println(age);
ra.close();
作者: 寇弘禄 时间: 2013-4-6 19:27
谢达 发表于 2013-4-6 19:00
RandomAccessFile ra = new RandomAccessFile("d:\\ran.txt","r");