日期:2014-05-20 浏览次数:20885 次
package javabook; import java.io.*; import java.util.*; //首先设计一个学生数据的类 class Student{ private String name; private int score; public Student(){ setName("noname"); } public Student(String name,int score){ setName(name); this.score=score; } public void setName(String name){ StringBuilder builder = null; if(name!=null) builder = new StringBuilder(name); else builder = new StringBuilder(15);//StringBuilder(int capacity) //构造一个不带任何字符的字符串生成器,其初始容量由 capacity 参数指定。 builder.setLength(15);//最长15个字符 1个字符占用2个字节 设置置字符序列的长度 this.name = builder.toString(); } public void setScore(int score){ this.score = score; } public String getName(){ return name; } public int getScore(){ return score; } public static int size(){ return 34; } } public class RandomAccess { 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(); /*将空字符取代为空格符并返回 *replace(char oldChar, char newChar) 返回一个新的字符串, *它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 *String(byte[] bytes) String的构造方面 */ return new String(name).replace('\0', ' '); } public static void main(String[] args){ Student[] students={ new Student("Justi",90), new Student("momor",95), new Student("Bush",88), new Student("catepillar",84) }; try{ File file = new File("student.data"); //如何没写"/",就是存在默认包里 /*System.out.println(file.getAbsolutePath()); *建立RandomAccessFile实例并以读写模式打开文件 "rw"表示读写模式 其中"r"表示读出 "w"表写入 可以用这3个其中1个 *RandomAccessFile(File file, String mode) RandomAccessFile(String name, String mode) */ RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw"); for(int i = 0;i<students.length;i++){ //使用对应的write方法写入数据 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()); //randomAccessFile.seek(0); 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){ e.printStackTrace(); } catch(FileNotFoundException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } } }