標籤:
package cn.stat.p2.demo;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;public class randomaccessfiledemo { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub radomwrite(); radomread(); } public static void radomread() throws FileNotFoundException, IOException { RandomAccessFile raf=new RandomAccessFile("demo.txt","rw"); byte[] buf=new byte[4]; raf.read(buf); String name=new String(buf); int age=raf.readInt(); System.out.println("name="+name); System.out.println("age="+age); //擷取指標位置 System.out.println("當前位置="+raf.getFilePointer()); //設定指標位置 raf.seek(1*12); System.out.println("age="+raf.readInt()); raf.close(); } public static void radomwrite() throws FileNotFoundException, IOException { RandomAccessFile raf=new RandomAccessFile("demo.txt","rw"); raf.write("張三".getBytes()); raf.writeInt(97); raf.write("趙六".getBytes()); raf.writeInt(98); raf.close(); }}
java下radomAccessFile檔案寫入讀取