📄 randomaccessfiledemo.java
字号:
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("读取第几个数据?");
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', ' ');
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -