RandomAccessFile类的主要功能是完成随机读取功能,可以读取指定位置的内容。负责对文件内容进行操作。
构造方法:
public RandomAccessFile(File file,String mode)
实例化此类的时候需要传递一个File类,告诉系统要操作哪个文件,之后有一个文件的打开模式:
写操作
package lianxijihe; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class lianxi042 { public static void main(String[] args){ File f = new File("F:\\abc.txt"); try { RandomAccessFile rdf = new RandomAccessFile(f, "rw"); String name = "ffffffff"; int age =30; rdf.writeBytes(name); rdf.writeInt(30); rdf.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
读操作
package lianxijihe; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class lianxi042 { public static void main(String[] args){ File f = new File("F:\\abc.txt"); try { RandomAccessFile rdf = new RandomAccessFile(f, "rw"); String name = ""; int age =0; byte b[] = new byte[8]; for(int i=0;i<b.length;i++){ b[i] = rdf.readByte(); } name = new String(b); age = rdf.readInt(); System.out.println(name); System.out.println(age); rdf.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
IO-02RandomAccessFile类,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u012897654/article/details/25653343