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

9 篇文章 0 订阅
 在访问文件时,文件就是一个大型的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") ;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值