Java的RandomAccessFile提供對文件的讀寫功能,與普通的輸入輸出流不同的是RamdomAccessFile能夠任意的訪問文件的任何地方。這就是「Random」的意義所在。
java
RandomAccessFile的對象包含一個記錄指針,用於標識當前流的讀寫位置,這個位置能夠向前移動,也能夠向後移動。RandomAccessFile包含兩個方法來操做文件記錄指針。dom
long getFilePoint():記錄文件指針的當前位置。ide
void seek(long pos):將文件記錄指針定位到pos位置。this
RandomAccessFile包含InputStream的三個read方法,也包含OutputStream的三個write方法。同時RandomAccessFile還包含一系列的readXxx和writeXxx方法完成輸入輸出。url
RandomAccessFile的構造方法以下spa
mode的值有四個.net
"r":以只讀文方式打開指定文件。若是你寫的話會有IOException。指針
"rw":以讀寫方式打開指定文件,不存在就建立新文件。orm
"rws":不介紹了。對象
"rwd":也不介紹。
[java] view plain copy
/**
* 往文件中依次寫入3名員工的信息,
* 每位員工有姓名和員工兩個字段 而後按照
* 第二名,第一名,第三名的前後順序讀取員工信息
*/
import java.io.File;
import java.io.RandomAccessFile;
public class RandomAccessFileTest {
public static void main(String[] args) throws Exception {
Employee e1 = new Employee(23, "張三");
Employee e2 = new Employee(24, "lisi");
Employee e3 = new Employee(25, "王五");
File file = new File("employee.txt");
if (!file.exists()) {
file.createNewFile();
}
// 一箇中文佔兩個字節 一個英文字母佔一個字節
// ××× 佔的字節數目 跟cpu位長有關 32位的佔4個字節
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
randomAccessFile.writeChars(e1.getName());
randomAccessFile.writeInt(e1.getAge());
randomAccessFile.writeChars(e2.getName());
randomAccessFile.writeInt(e2.getAge());
randomAccessFile.writeChars(e3.getName());
randomAccessFile.writeInt(e3.getAge());
randomAccessFile.close();
RandomAccessFile raf2 = new RandomAccessFile(file, "r");
raf2.skipBytes(Employee.LEN * 2 + 4);
String strName2 = "";
for (int i = 0; i < Employee.LEN; i++) {
strName2 = strName2 + raf2.readChar();
}
int age2 = raf2.readInt();
System.out.println("strName2 = " + strName2.trim());
System.out.println("age2 = " + age2);
raf2.seek(0);
String strName1 = "";
for (int i = 0; i < Employee.LEN; i++) {
strName1 = strName1 + raf2.readChar();
}
int age1 = raf2.readInt();
System.out.println("strName1 = " + strName1.trim());
System.out.println("age1 = " + age1);
raf2.skipBytes(Employee.LEN * 2 + 4);
String strName3 = "";
for (int i = 0; i < Employee.LEN; i++) {
strName3 = strName3 + raf2.readChar();
}
int age3 = raf2.readInt();
System.out.println("strName3 = " + strName3.trim());
System.out.println("age3 = " + age3);
}
}
class Employee {
// 年齡
public int age;
// 姓名
public String name;
// 姓名的長度
public static final int LEN = 8;
public Employee(int age, String name) {
this.age = age;
// 對name字符長度的一個處理
if (name.length() > LEN) {
name = name.substring(0, LEN);
} else {
while (name.length() < LEN) {
name = name + "/u0000";
}
}
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}