总结出处:http://www.cnblogs.com/lich/archive/2011/12/10/2283445.html
之前的File类只是针对文件本身进行操作的,而如果相对文件内容进行操作,则可以使用RandomAccessFile类,此类属于随即读取类,可以随机的读取一个文件中指定位置的数据。因为在文件中,所有得内容都是按照字节存放的,都有固定的保存位置。
public static void randomAccessFormText() throws IOException{ File file = new File("C://Users//Administrator//Desktop"+File.separator+"basic"+File.separator+"ftxt2.txt"); RandomAccessFile rf = new RandomAccessFile(file, "rw"); String name1 = "肖"; int age1 = 10; String name2="tto"; int age2 = 26; rf.writeUTF(name1); rf.writeInt(age1); rf.writeBytes(name2); rf.writeInt(age2); rf.close(); RandomAccessFile raf = new RandomAccessFile(file, "r"); raf.skipBytes(9); byte[] bs = new byte[3]; for(int i=0;i<bs.length;i++){ bs[i] = raf.readByte(); } String n2 = new String(bs); int ag2 = raf.readInt(); System.out.println(n2+"/t"+ag2); raf.seek(0); System.out.println(raf.readUTF()+"/t"+raf.readInt()); }新闻热点
疑难解答