歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中RandomAccessFile類用法

Java中RandomAccessFile類用法

日期:2017/3/1 10:06:51   编辑:Linux編程

Java中RandomAccessFile類
只能訪問文件,不能操作其他io設備
支持隨機訪問
在讀寫等長記錄文件有優勢

實例:

import java.io.*;

class Employee {
private String name;
private int age;
public static final int LEN = 8;

String getName() {
return name;
}

int getAge() {
return age;
}

Employee(String name, int age) {
if (name.length() > LEN) { // 為了構造等長記錄
this.name = name.substring(0, LEN-1);
} else {
this.name = name;
while (this.name.length() < LEN) {
this.name += '\u0000';
}
}
this.age = age;
}
}

public class RandomAccessFileTest {
public static void main(String [] args) {
Employee e1 = new Employee("Ronnie", 37);
Employee e2 = new Employee("John", 37);
Employee e3 = new Employee("Mark", 37);

try {
RandomAccessFile randFile = new RandomAccessFile("employee.txt", "rw");

//randFile.write(e1.getName().getBytes()); // 如果name有中文,會出現問題,因為一個英文字符轉換為一個字節,一個中文字符轉換為兩個字節,可以用writeChars函數改寫
randFile.writeChars(e1.getName()); //-
randFile.writeInt(e1.getAge());
//randFile.write(e2.getName().getBytes());
randFile.writeChars(e1.getName()); //-
randFile.writeInt(e2.getAge());
//randFile.write(e3.getName().getBytes());
randFile.writeChars(e1.getName()); //-
randFile.writeInt(e3.getAge());

randFile.close();
} catch (Exception e) {
e.printStackTrace();
}

try {
//byte[] nameBuf = new byte[Employee.LEN];

RandomAccessFile randFile = new RandomAccessFile("employee.txt", "r");

//randFile.skipBytes(12);
randFile.skipBytes(20); //-
//int len = randFile.read(nameBuf);
//String name = new String(nameBuf, 0, len);
String name = "";//-
for (int i = 0; i < Employee.LEN; ++i) { //-
name += randFile.readChar(); //-
}//-
System.out.println(name.trim() + ":" + randFile.readInt());
name = ""; //-

randFile.seek(0); // 絕對定位
//len = randFile.read(nameBuf);
//name = new String(nameBuf, 0, len);
for (int i = 0; i < Employee.LEN; ++i) { //-
name += randFile.readChar(); //-
} //-
System.out.println(name.trim() + ":" + randFile.readInt());
name = ""; //-

//randFile.skipBytes(12);
randFile.skipBytes(20); //-
//len = randFile.read(nameBuf);
//name = new String(nameBuf, 0, len);
for (int i = 0; i < Employee.LEN; ++i) { //-
name += randFile.readChar(); //-
} //-
System.out.println(name.trim() + ":" + randFile.readInt());

randFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

注釋部分為按字節寫入時的程序,帶//-為原來的代碼

其他函數請參照jdk文檔

Copyright © Linux教程網 All Rights Reserved