package com.zl;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFile1
{
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
Person p = new Person(1,"hello",5.42);
RandomAccessFile raf = new RandomAccessFile("teast.txt","rw");
p.write(raf);
Person p2 = new Person();
raf.seek(0);// 让读得位置回到文件开头
p2.read(raf);
System.out.println(p2);
}
}
class Person
{
private int id;
@Override
public String toString()
{
return "Person [id=" + id + ", name=" + name + ", height=" + height
+ "]";
}
public Person()
{
}
public Person(int id, String name, double height)
{
this.id = id;
this.name = name;
this.height = height;
}
private String name;
private double height;
public void write(RandomAccessFile file) throws Exception
{
file.write(this.id);
file.writeUTF(this.name);
file.writeDouble(this.height);
}
public void read(RandomAccessFile file) throws IOException
{
this.id = file.readInt();
this.name = file.readUTF();
this.height = file.readDouble();
}
}
报这个异常
Exception in thread "main" java.io.EOFException
但是我这里明明 raf.seek(0);// 让读得位置回到文件开头,为何还是报呢
------解决方案--------------------
写完了,你要把stream关掉啊,然后再重新读,不关掉还是个空文件,自然会报错。
------解决方案--------------------
把stream关掉