package IO;
import java.io.RandomAccessFile;
public class RandomAccessFile1
{
public static void main(String[] args)throws Exception
{
RandomAccessFile raf = new RandomAccessFile("F:/abc/a.java","rw");
person p = new person(2,"nihao",5.22);
p.write(raf);
raf.seek(0);
person p2 = new person();
p2.read(raf);
System.out.println(p2.getAge() + "; " + p2.getName() + " ;" + p2.getHeight() );
}
}
class person
{
int age;
String name;
Double height;
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
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;
}
public person()
{
}
public person(int age,String name,Double height)
{
this.age = age;
this.name = name;
this.height = height;
}
public void write(RandomAccessFile raf)throws Exception
{
raf.writeInt(this.age);
raf.writeUTF(this.name);
raf.writeDouble(this.height);
}
public void read(RandomAccessFile raf)throws Exception
{
this.age = raf.readInt();
this.name = raf.readUTF();
this.height = raf.readDouble();
}
}
seek(偏移量)表示文件从头开始读取,读取的格式需要与写入的格式一样,这样不容易出现乱码
ASCII 美国信息互换标准代码 128 个码
GB2313 中国编码格式
GBK 扩展的中文编码格式
ISO 仅支持西文
Unicode 将英文也用两个字节表示,英文也采用两个字节,第一个字节加零字节表示
UTF-8可以容纳各种编码格式