[javaSE] IO流(RandomAccessFile)

随机访问文件,可以看作一个大型的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));//输出  李小明
    }
}
原文地址:https://www.cnblogs.com/taoshihan/p/5568374.html