RandomAccessFile类
//RandomAccessFile的演示
public class RandomAccessFileDemo {
public static void main(String[] args) throws IOException {
//创建文件路径字符串
String file = "D:/java.java";
writeFile(file);
readFile(file);
}
//
private static void readFile(String file) throws IOException {
//创建具有读权限的RanddomAccessFile对象,注意需要抛出找不到文件异常FileNotFoundException
RandomAccessFile raf = new RandomAccessFile(file,"r");
//返回当前偏移量,主要要抛出IOExcepiton
System.out.println("当前偏移量" + raf.getFilePointer());
StringBuilder sb = new StringBuilder();
//既读取zhangsan
for (int i = 0; i < 8; i++) {
//readByte()为从文件读取一个有符号的八位值.
sb.append((char)raf.readByte());
}
System.out.println("name :" + sb);
System.out.println("当前偏移量" + raf.getFilePointer());
//返回一个4个字节的int类型
System.out.println("age= " + raf.readInt());
//跳过八个字节,既跳过 "huangkuh"
raf.skipBytes(8);
//读取kunhuang
for (int i = 0; i < 8; i++) {
sb.append((char)raf.readByte());
}
System.out.println("name:" + sb);
System.out.println("当前偏移量" + raf.getFilePointer());
System.out.println("age:" + raf.readInt());
//关闭
raf.close();
}
//往文件写入数据
private static void writeFile(String file) throws IOException {
//创建具有读写权限的RandomAccessFile对象,注意需要抛出找不到文件异常
RandomAccessFile raf = new RandomAccessFile(file,"rw");
//wtite写入字符串,参数为byte数组,注意需要抛出IO异常
raf.write("zhangsan".getBytes());
//write按四个字节写入整型,
raf.writeInt(11);
raf.write("huangkuh".getBytes());
raf.writeInt(23);
raf.write("kunhuang".getBytes());
raf.writeInt(34);
//关闭
raf.close();
}
}