package cn.itcast02; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteOrder; public class DemoRandowAccessFile01 { public static void main(String[] args) throws IOException { File file = new File("G:" + File.separator +"JavaTest"+File.separator + "test01.txt" ); /* RandomAccessFile rdf = new RandomAccessFile(file, "rw"); //寫入文件內容 String name = " liuyan "; int age = 40; rdf.writeBytes(name); rdf.writeInt(age); String name2 = " xiaoming"; int age2 = 30; rdf.writeBytes(name2); rdf.writeInt(age2); String name3 = " doudou "; int age3 = 24; rdf.writeBytes(name3); rdf.writeInt(age3); rdf.close(); */ //讀取文件內容 RandomAccessFile rdf = new RandomAccessFile(file, "r" ); //創建空間存放姓名 byte[] bytes = new byte[8]; rdf.skipBytes(12); for (int i = 0; i < bytes.length; i++) { bytes[i] = rdf.readByte(); } //將byte轉化為String String name = new String(bytes); int age = rdf.readInt(); System. out.println("第二個人信息" +"姓名:" +name+" " +"年齡:" +age); //指針返回到文件開頭 rdf.seek(0); rdf.close(); } }
輸出:
第二個人信息姓名:xiaoming 年齡:30