当前位置: 代码迷 >> Java Web开发 >> 请教各位
  详细解决方案

请教各位

热度:243   发布时间:2008-04-25 03:21:34.0
请教各位
public class Student {
    private String name;
    private int score;
    public Student()
    {
        setName("noname");
    }
    public Student(String name,int score)
    {
        setName(name);
        this.score=score;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        StringBuilder builder=null;
        if(name!=null)
        builder=new StringBuilder(name);
        else
            builder=new StringBuilder(15);
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public static int size()
    {
        return 34;
    }
}
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;

public class RandomAccessFileDemo {

    public static void main(String[] args) {
        Student[] students = { new Student("zhangsheng", 90),
                new Student("liyuan", 92), new Student("goofy", 90) };
        try {
            File file = new File(args[0]);
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

            for (int i = 0; i < students.length; i++) {
                randomAccessFile.writeChars(students[i].getName());
                randomAccessFile.writeInt(students[i].getScore());
            }
            Scanner scanner = new Scanner(System.in);
            System.out.print("读取第几个数据");
            int num = scanner.nextInt();
            randomAccessFile.seek((num-1) * Student.size());
            Student student = new Student();
            student.setName(readName(randomAccessFile));
            student.setScore(randomAccessFile.readInt());
            System.out.println("姓名:" + student.getName());
            System.out.println("分数:" + student.getScore());
            randomAccessFile.close();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("请指定文件名称");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static String readName(RandomAccessFile randomAccessFile)
            throws IOException {
        char[] name = new char[15];
        for (int i = 0; i < name.length; i++)
            name[i] = randomAccessFile.readChar();
        return new String(name).replace('\0', ' ');
    }

}
良哥哥的书上的例子,运行怎么就抛出ArrayIndexOutOfBoundsException异常啊?在Eclipse上运行的
----------------解决方案--------------------------------------------------------
ms
数据字节不统一
----------------解决方案--------------------------------------------------------
  相关解决方案