JAVA IO:RandomAccessFile

来源:互联网 发布:淘宝金冠店多少 编辑:程序博客网 时间:2024/06/08 05:46

RandomAccessFile

强大之处在于能够随机访问文件的任意位置,并能够写入内容,这是fileinputstream和fileoutputstream不具有的功能,尤其在对大文件处理,追加内容时候,这个特性很有用

两个特殊的方法,其他的和其他i/o类没有区别,使用完也要记得关闭

getFilePointer():获取当前文件指针的位置

seek(long index):文件指针指向这个位置

创建 RandomAccessFile raf = new RandomAccessFile(file,String mode);

mode:

r:只读的方式打开文件

w:只写

rw:读写方式打开文件

rwd:读写方式打开,对文件内容的更新同步更新至底层存储设备

rws:读写方式打开,对文件内容的更新同步更新至底层存储设备

文件1.txt


读取:

public static void main(String[] args) {File file = new File("C:\\Users\\admin\\Desktop\\1.txt");try {java.io.RandomAccessFile raf = new java.io.RandomAccessFile(file, "r");long filePointer = raf.getFilePointer();System.out.println("当前文件指针的位置:"+filePointer);//移动指针 多少个字节raf.seek(8);byte[] by = new byte[1024];int length = -1;while((length=raf.read(by, 0, by.length))!=-1){String str = new String(by, 0, length);System.out.println("读取文件的内容:"+str);}raf.close();} catch (FileNotFoundException e) {e.printStackTrace();}catch (IOException e){e.printStackTrace();}}
运行结果;

写入:

public static void main(String[] args) {File file = new File("C:\\Users\\admin\\Desktop\\1.txt");try {java.io.RandomAccessFile raf = new java.io.RandomAccessFile(file, "rw");long filePointer = raf.getFilePointer();System.out.println("当前文件指针的位置:"+filePointer);//移动指针 多少个字节raf.seek(file.length());String str = " add data \n";raf.write(str.getBytes());raf.close();} catch (FileNotFoundException e) {e.printStackTrace();}catch (IOException e){e.printStackTrace();}}

运行结果:


RandomAccessFile可以实现多线程断点下载的功能,断点下载前都会建立两个临时文件,一个是和被下载文件大小相同的空文件,一个是记录文件指针的位置文件,每次暂停的时候,保存上一次的指针,然后继续下载的时候,从上一次位置下载,从而实现断点下载或上传的功能

转载自http://blog.csdn.net/czplplp_900725/article/details/37809579