Java中RandomAccessFile类_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java中RandomAccessFile类

Java中RandomAccessFile类

 2018/10/24 12:18:34  andrew7676  程序员俱乐部  我要评论(0)
  • 摘要:1.RandomAccessFile类1.使用RandomAccessFile访问文件的部分内容importjava.io.RandomAccessFile;publicclassRandomAccessFile1{publicstaticvoidmain(String[]args)throwsException{Personp=newPerson(1,"hello",5.42);RandomAccessFileraf=newRandomAccessFile("test.txt","rw")
  • 标签:Access file Java Mac
1. RandomAccessFile类
class="java">
1. 使用RandomAccessFile访问文件的部分内容
import java.io.RandomAccessFile;
public class RandomAccessFile1 {
    public static void main(String[] args) throws Exception {
        Person p = new Person(1, "hello", 5.42);
        RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
        p.write(raf);
        Person p2 = new Person();
        raf.seek(0);// 让读的位置重回到文件开头
        p2.read(raf);
        System.out.println(p2.getId() + ", " + p2.getName() + ", "
                + p2.getHeight());
    }
}
class Person{
    int id;
    String name;
    double height;
    public void write(RandomAccessFile raf) throws Exception{
        raf.writeInt(this.id);
        raf.writeUTF(this.name);
        raf.writeDouble(this.height);
    }
    public void read(RandomAccessFile raf) throws Exception{
        this.id = raf.readInt();
        this.name = raf.readUTF();
        this.height = raf.readDouble();
    }
    public Person() {}
    public Person(int id, String name, double height) {
        this.id = id;
        this.name = name;
        this.height = height;
    }
    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public double getHeight() {return height;}
    public void setHeight(double height) {this.height = height;}
}
发表评论
用户名: 匿名