关于RandomAccessFile的问题。

channel321 2012-09-16 02:06:18
public class output{
public static void main (String[] arg) throws Exception{
File file= new File("D:\\jdk1.6\\jdk1.6\\new.txt");
RandomAccessFile raf = new RandomAccessFile(file,"rw");
String name ="张三凑够八个数字";
int age =30;
raf.writeBytes(name);
raf.writeInt(age);
String name2 ="lisi";
int age2 =31;
raf.writeBytes(name2);
raf.writeInt(age2);
String name3 ="wangwu";
int age3 =33;
raf.writeBytes(name3);
raf.writeInt(age3);
raf.close();
}
}
------------------------------------------------
public class input{
public static void main (String[] arg) throws Exception{
File file= new File("D:\\jdk1.6\\jdk1.6\\new.txt");
RandomAccessFile raf = new RandomAccessFile(file,"rw");
byte[] a =new byte[12];
String name ="";
int age=0;
raf.skipBytes(12);
System.out.println("第二个人信息");
for(int i=0;i<8;i++){
a[i] =raf.readByte();
}
age=raf.readInt();
System.out.println("姓名:"+new String(a));
System.out.println("年龄:"+age);
raf.seek(0);
System.out.println("第一个人信息:");
for(int i=0;i<8;i++){
a[i] =raf.readByte();
}
age =raf.readInt();
System.out.println("姓名:"+new String(a));
System.out.println("年龄:"+age);
raf.close();
}


}
两个类,先写入再读取。问题是在于读取那里,为什么skipByte是跳过12个字节?不是应该跳过20个么?"zhangsan"是占16位不是么。?后面的年龄30是int,占4位?按他这里的算法不是把zhangsan当成是8位了???我记得String就是一个char数组,char是占两个的。。望各位能给个详细解释,谢谢大家
...全文
194 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
rockets311 2012-09-16
  • 打赏
  • 举报
回复
第一个问题:按照楼主的理解就OK了。
第二个问题:其实跟第一个问题也有点联系,详细说一下:看一下writeBytes的说明:Writes the string to the file as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits. The write starts at the current position of the file pointer.
也就是说,它丢弃了这个字符的最高八位,楼主也说了,一个字符是两个字节,它丢弃了最高八位,剩下的就为一个字节了,所以它写入的内容并不全,第一个问题的原因就找到了。用writeChars就写全了:可以看一下writeChars的说明:Writes a string to the file as a sequence of characters. Each character is written to the data output stream as if by the writeChar method. The write starts at the current position of the file pointer.那接着看一下writeChar这个方法的说明:Writes a char to the file as a two-byte value, high byte first. The write starts at the current position of the file pointer.可见,这个方法是把一个字符的两个字节都写进去了,所以,写字符串的时候建议用这个方法,而对应的读取的时候就用readChar这个方法了。
channel321 2012-09-16
  • 打赏
  • 举报
回复
还有个问题。。当设置成12的时候。输出如下:
第二个人信息
姓名:lisi
年龄:2002873959
第一个人信息:
姓名: ?k*pW
年龄:30

为什么第一个年龄又不能正确显示。第二个却可以。o(╯□╰)o
channel321 2012-09-16
  • 打赏
  • 举报
回复
我试过按自己 想法设置成20.。然后就报错了。。Exception in thread "main" java.io.EOFException
at java.io.RandomAccessFile.readInt(RandomAccessFile.java:725)
at input.main(input.java:14)

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧