randomaccessfiledemo.java
来自「一些基本的java程序源代码」· Java 代码 · 共 45 行
JAVA
45 行
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 + =
减小字号Ctrl + -
显示快捷键?