本帖最后由 taomingking 于 2013-7-29 21:30 编辑
这个道理很简单的,你writeFile()方法存入的wang wu是7个字节,writeInt()存入的4是4个字节,但是你readFile()方法里却是先读了10个字节,再用readInt()读取了4个字节,把zhao si的前三个字节读取了出来.
总的来说就是你存入和读取的字节数不一致,导致这种情况
下面是代码我更改了一下- package com.itheima;
- import java.io.*;
- class RandomAccessFileDemo
- {
- public static void main(String[] args) throws IOException
- {
- writeFile();
- System.out.println("wang wu".getBytes().length);//打印一下wang wu的字节数
- readFile();
- //System.out.println(Integer.toBinaryString(259));
- }
- public static void readFile() throws IOException
- {
- RandomAccessFile raf = new RandomAccessFile("ram.txt","r");
-
- byte[] buf=new byte[7];//这里改成7就可以了
- raf.read(buf);
- String name=new String(buf);
- int age=raf.readInt();
-
- System.out.println("name="+name);
- System.out.println("age="+age);
- }
- public static void writeFile() throws IOException
- {
- RandomAccessFile raf=new RandomAccessFile("ram.txt","rw");
- raf.write("wang wu".getBytes());//存入的是7个字节
- //raf.write(66);
- raf.writeInt(4);
- raf.write("zhao si".getBytes());
- //raf.write(66);
- raf.writeInt(333333333);
- raf.close();
- }
- }
复制代码 |