隨機訪問文件,可以看作一個大型的byte[]數組,不算是IO體系中的一員,內部封裝了字節輸入輸出流,可以設置權限,可以調整指針的位置
獲取RandomAccessFile對象,構造參數:String文件名稱,String的文件模式
調用RandomAccessFile對象的write()方法,參數:byte[]數組
獲取RandomAccessFile對象,構造參數:String文件名稱,String的文件模式
調用RandomAccessFile對象的seek()方法,調整指針位置,參數:int的索引位置
調用RandomAccessFile對象的skipBytes()方法,可以跳過指定索引,參數:int索引位置
多線程下載的原理就是使用這個類
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//寫入
RandomAccessFile raf=new RandomAccessFile("test2.txt", "rw");
raf.write("陶士涵李小明".getBytes());
raf.close();
//讀取
readFile();
}
public static void readFile() throws Exception{
RandomAccessFile raf=new RandomAccessFile("test2.txt", "rw");
raf.seek(6);//調整指針位置
byte[] b=new byte[1024];
int len=raf.read(b);
raf.close();
System.out.println(new String(b,0,len));//輸出 李小明
}
}