黑马程序员技术交流社区

标题: 怎么写这两句就报错呢? [打印本页]

作者: 寇弘禄    时间: 2013-4-6 18:36
标题: 怎么写这两句就报错呢?
本帖最后由 寇弘禄 于 2013-4-6 19:27 编辑
  1. package time20120406;

  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.io.RandomAccessFile;

  5. public class RandomAccessDemo {

  6.         /**
  7.          * @param args
  8.          * @throws IOException
  9.          */
  10.         public static void main(String[] args) throws IOException {
  11.                 WriteMethod();
  12.                 ReadMethod();
  13.         }
  14.         public static void WriteMethod() throws IOException{
  15.                 RandomAccessFile ra = new RandomAccessFile("d:\\ran.txt","rw");
  16.                 ra.write("王五".getBytes());
  17.                 ra.writeInt(22);
  18.                 ra.close();
  19.         }
  20.         public static void ReadMethod() throws IOException{
  21.                 RandomAccessFile ra = new RandomAccessFile("d:\\ran.txt","r");
  22.                 byte[] buf = new byte[1024];
  23.                 int len = ra.read(buf);
  24.                 String name = new String(buf,0,len);
  25.                 int age = ra.readInt();
  26.                 System.out.println(name);
  27.                 System.out.println(age);
  28.                 ra.close();
  29.         }
  30. }
复制代码
报的是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");

                byte[] buf = new by ...

谢谢,是这的问题。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2