import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;import sun.font.EAttribute;
public class RandomAccessFileDemo {
public static void main(String[] args) {
Student[] students={
new Student("Justin",90),
new Student("momor",95),
new Student("Bush",88),
new Student("caterpillar",84)
};
try{
File file=new File(args[0]);
//建立RandomAccessFile实例并以读写模式打开文件
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();
//使用seek()方法操作存取位置
randomAccessFile.seek((num-1)*Student.size());
Student student=new Student();
//使用对应的read方法读取数据
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', '0');
}
}
这个程序为什么只执行catch语句,为什么不执行try语句,怎么才能执行try语句

解决方案 »

  1.   

    你执行这个类的时候要指定参数。
    如果不指定args[0]是空的。肯定要抛出异常的!
      

  2.   

    伙记,这问题你需要去看看JAVA的异常处理,
    看了不懂再来问
    要多学,自学.
      

  3.   

    运行的时候用java RandomAccessFileDemo "d:\a.txt"
      

  4.   

    我是初学者,能再具体讲一下吗?书上的执行结果是:
    java RandomAccessFileDemo student.dat
    读取第几个数据?2
    姓名:momor
    分数:95
    以上的结果我为什么运行不出来呢?我要怎么做才能运行出来正确的结果,请各位指教