利用RandomAccessFile对文件进行切割存储

来源:互联网 发布:空手道数据集 编辑:程序博客网 时间:2024/05/01 18:39
 在访问文件时,文件就是一个大型的byte数组,存在指向该隐含数组的光标或索引,称为文件指针。 RandomAccessFile的实例对象,可以通过挪动该指针,有选择性的获取文件中的内容。
利用RandomAccessFile可以做到将大型文件对应的数组切割,用多个byte[]数组去装,然后分批上传即可/或者可以用于断点续传上传或下载文件。
    首先,先用RandomAccessFile读取文件:
byte[] result = new byte[3];//声明一个数组,需要多大自己设定,大小决定它每次读取文件的长度RandomAccessFile rf = new RandomAccessFile(Environment.getExternalStorageDirectory().getPath() + "/" + "_3SdkSendAckToService.txt", "rw");//实例化RandomAccessFile对象Log.e(TAG, "setRamdomFile: " + rf.length());//RandomAccessFile对象读出文件的长度rf.read(result);//将RandomAccessFile读如数组中String showContent = new String(result);//将数组转为字符串long currentIndex = rf.getFilePointer();//获得RandomAccessFile读到的位置Log.e(TAG, "setRamdomFile: " + showContent + "\n" + currentIndex);
      
     利用seek将指针指向指定位置
rf.seek(18);//将当前光标移动到指定位置
rf.read(result);//继续读取文件
showContent = new String(result);
currentIndex = rf.getFilePointer();
Log.e(TAG"setRamdomFile2: " + showContent + "\n+ currentIndex);


    将读到的数据写入新的文件中
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" "newText.txt");
if (!file.exists()) {
    File dir = new File(file.getParent());
    dir.mkdirs();
    file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(result);
fileOutputStream.close();
getFile("newText.txt");
原创粉丝点击