?? randomaccessfiledemo.java
字號(hào):
package randomaccess.file.randomaccessfiledemo;
import java.io.*;
import java.util.*;
import randomaccess.file.student.Student;
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("cater",86) };
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("讀取第幾個(gè)數(shù)據(jù)?");
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("分?jǐn)?shù):"+student.getScore());
randomAccessFile.close();
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("請(qǐng)指定文件名稱");
}
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', ' ');
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -