A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 寇弘禄 中级黑马   /  2013-4-6 18:36  /  1683 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 寇弘禄 于 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 这个错误。看着和视频里没太大区别啊??

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

2 个回复

倒序浏览
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();

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

回复 使用道具 举报
谢达 发表于 2013-4-6 19:00
RandomAccessFile ra = new RandomAccessFile("d:\\ran.txt","r");

                byte[] buf = new by ...

谢谢,是这的问题。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马