欢迎光临散文网 会员登陆 & 注册

随机流输出文件的代码

2020-04-05 12:41 作者:小垃圾kiki  | 我要投稿
package cn.jd.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/*
 * 随机读取和写入流RandomAccessFile
 *
 */
public class RandTest04 {
    public static void main(String[] args) throws IOException {
        //分多少块   首先给一个需要分块的文件
        File src=new File("src/cn/jd/io/Copy.java");
        //文件的总长度
        long  len=src.length();
//        System.out.println(len);
        //每块大小
        int  blockSize=1024;
        //分多少块
        int size=(int)Math.ceil(len*1.0/blockSize);//向上取整的意思就是3.5变成4
//        double a=6.0;
//        int b=4;
//        System.out.println(a/b);
        //思路每一块从哪里开始到哪里结束
        int beginPos=0;
        int actualSize=(int)(blockSize>len?len:blockSize);  //如果blockSize大于len,那么就选len的长度
        for(int i=0;i<size;i++) {
            beginPos=i*blockSize;
            if(i==size-1) {//最后一块
                actualSize=(int)len;
            }else {
                actualSize=blockSize;
                len-=actualSize;//剩余长度
            }
            System.out.println(i+"-->"+beginPos+"-->"+actualSize);
            test2(i,beginPos,actualSize);//里面的参数一定要和下面的方法对应,出现问题就debug调试一下
        }
        
        
        
    }
    
    //分块思想:有了起始索引,有了实际大小
    //指定第i块的起始位置和实际长度
    public static void test2(int i,int beginPos,int actualSize) throws IOException {
        RandomAccessFile  raf=new RandomAccessFile(new File("src/cn/jd/io/Copy.java"), "r");
        //加入写出模式
        RandomAccessFile  raf2=new RandomAccessFile(new File("dest/"+i+"Copy.java"), "rw");
//        //起始位置
//        int beginPos=2;
//        //实际大小
//        int actualSize=1026;//我要读取1026个字节
//        //随机读取
        raf.seek(beginPos); //从第二个索引开始读取,记住索引是从0开始的
        //读取    读取方式和字节流的读取方式是一样的
        byte[]  flush=new byte[1024];
        int len=-1;
        while((len=raf.read(flush))!=-1) {
            
            if(len<=actualSize) {//获取本次读取的所有内容
//                System.out.println(new String(flush,0,len));
                raf2.write(flush,0,len);
//                actualSize-=len;//还剩余多少字节需要下次读取
                break;
            }else {
//                System.out.println(new String(flush,0,actualSize));
                raf2.write(flush,0,actualSize);
                break;
            }
        }
        
        raf2.close();
        raf.close();
    }

}

随机流输出文件的代码的评论 (共 条)

分享到微博请遵守国家法律