JAVA_RandomAccess类操作

package com.kk.review;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAcessFileTest {
public static void main(String[] args) {
try {
RandomAccessFile file=new RandomAccessFile("a.txt","rw"); //rw:读写
Student kk=new Student("kk",'男',22);
kk.write(file);
file.seek(0);//将指定位到文件开始位置
kk.read(file);
kk.toString();
file.seek(0);
kk.readByPointer(file);//根据filePointer遍历文件模式
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

class Student {
String name;

char gender;

int age;

public Student() {
}

void write(RandomAccessFile file) throws IOException {
file.writeUTF(this.getName());
file.writeChar(this.getGender());
file.writeInt(this.getAge());
}

void read(RandomAccessFile file) throws IOException {
this.setName(file.readUTF());
this.setGender(file.readChar());
this.setAge(file.readInt());
}

/**
* 根据file.getFilePointer循环读取
*
@param file
*
@throws IOException
*/
void readByPointer(RandomAccessFile file)throws IOException{
for (long i = 0; i < file.length(); i=file.getFilePointer()) {
System.out.println(file.readUTF());
System.out.println(file.readChar());
System.out.println(file.readInt());
}
}

@Override
public String toString() {
System.out.println("name:".concat(getName()).concat("\rgender:")
.concat(getGender() + "\r").concat("age:").concat(
getAge() + "\r"));
return null;
}

public Student(String name, char gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public char getGender() {
return gender;
}

public void setGender(char gender) {
this.gender = gender;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

你可能感兴趣的:(Access)