Java的简单理解(25)---(随机访问文件)RandomAccessFile

Java

RandomAccessFile

/**
 * 文件的分割
 * 1. 分割的块数     n块
 * 2. 每一块的大小   blocksize
 * 3. 最后:总的文件大小 - (n - 1) * blocksize
 */
public void test(){

    try {
        File file = new File("E:/xp/test/a.txt");
        RandomAccessFile rnd = new RandomAccessFile(file,"r");

        rnd.seek(10);
        byte[] car = new byte[1024];
        int len = 0;

        while ((len = rnd.read(car)) != -1) {
            if (len >= 200) {
                System.out.println(new String(car,0,120));
            } else {
                System.out.println(new String(car,0,len));
            }
        }

        rnd.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

文件分割的思路

  • 第一步:分割的准备
    • 块数
    • 确定每块大小
    • 每块的名称
  • 第二步
    • 分割
    • 第几块,每块的起点,实际大小
    • 文件分割
public class SplitFile {

    // 文件的路径
    private String filePath;

    // 文件名
    private String fileName;

    // 文件大小
    private long length;

    // 块数
    private int size;

    // 每块的大小
    private long blockSize;

    // 每块的名称
    private List<String> blockPath;

    public SplitFile() {
        blockPath = new ArrayList<>();
    }

    public SplitFile(String filePath) {
        this(filePath,1024);
    }

    public SplitFile(String filePath,long blockSize){
        this();
        this.filePath = filePath;
        this.blockSize = blockSize;
        init();
    }

    /**
     * 初始化操作,计算块数,确定文件名
     */
    public void init() {
        File src = null;
        if (filePath == null || !((src = new File(filePath)).exists())){
            return;
        }

        if (src.isDirectory()) {
            return;
        }

        // 文件名
        this.fileName = src.getName();

        // 文件的实际大小
        this.length = src.length();

        // 修正每块大小
        if (this.blockSize > length) {
            this.blockSize = length;
        }
        // 确定块数
        size = (int) Math.ceil(length * 1.0 / this.blockSize);

    }

    /**
     * 确定文件名
     */
    public void initPathName(String destPath) {
        for (int i = 0; i < size; i++){
            this.blockPath.add(destPath + "/" + this.fileName + ".part" + i);
        }
    }

    /**
     * 文件的分割
     * @param destPath 分割文件存放目录
     */
    public void split(String destPath){

        // 确定文件的路径
        initPathName(destPath);

        long beginPos = 0;// 起始点
        long actualBlockSize = blockSize;//实际大小

        // 计算所有块的大小
        for (int i = 0; i < size; i++) {

            if (i == size - 1){
                actualBlockSize = this.length - beginPos;
            }

            spiltDetail(i,beginPos,actualBlockSize);
            beginPos = beginPos + actualBlockSize;
        }
    }

    /**
     * 文件的分割 输入 输出
     * 文件的拷贝
     * @param idx 第几块
     * @param beginPos 起始点
     * @param actualBlockSize 实际大小
     */
    public void spiltDetail(int idx,long beginPos,long actualBlockSize){
        // 1. 创建源
        File src = new File(this.filePath);
        // 2. 目标文件
        File dest = new File(this.blockPath.get(idx));
        // 3. 选择流
        RandomAccessFile raf = null;
        BufferedOutputStream bos = null;
        try {
            raf = new RandomAccessFile(src,"r");
            bos = new BufferedOutputStream(new FileOutputStream(dest));

            // 读取文件
            raf.seek(beginPos);
            // 缓存
            byte[] flush = new byte[1024];
            // 接收长度
            int len = 0;
            while (-1 != (len = raf.read(flush))) {
                // 写出
                if (actualBlockSize - len >= 0) {
                    bos.write(flush,0,len);
                    actualBlockSize = actualBlockSize - len;
                } else {
                    bos.write(flush,0, (int) actualBlockSize);
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

合并文件的两种方法
1.
public void mergeFile1(String destPath) {
    // 创建源
    File dest = new File(destPath);
    // 选择流
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    try {
        bos = new BufferedOutputStream(new FileOutputStream(dest,true)); // true: 追加而不是替换
        for (int i = 0; i < this.blockPath.size(); i++) {
            bis = new BufferedInputStream(new FileInputStream(new File(blockPath.get(i))));

            // 缓冲区
            byte[] flush = new byte[1024];
            // 接收长度
            int len = 0;
            while ((len = bis.read(flush)) != -1) {
                bos.write(flush,0,len);
            }

            bos.flush();

            bis.close();
            bos.close();

        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
2.
public void mergeFile2(String destPath) {
    // 创建源
    File file = new File(destPath);

    // 选择流
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    SequenceInputStream sis = null;

    // 创建一个容器
    Vector<InputStream> vector = new Vector<>();

    for (int i = 0; i < this.blockPath.size(); i++){
        try {
            vector.add(new BufferedInputStream(new FileInputStream(new File(blockPath.get(i)))));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    try {
        bos = new BufferedOutputStream(new FileOutputStream(file,true));
        sis = new SequenceInputStream(vector.elements());

        byte[] flush = new byte[1024];
        int len = 0;

        while ((len = sis.read(flush)) != -1) {
            bos.write(flush,0,len);
        }

        bos.flush();

        bos.close();
        bis.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • 石家庄:10.15当日所有结算均超时。10.16修改所有结算单状态,进行手动结算时,发现多结算了一笔 银行核心反馈...
    and天神阅读 308评论 0 0
  • 深入理解闭包: 一、变量的作用域 要理解闭包,首先必须理解Javascript特殊的变量作用域。 变量的作用域无非...
    老头子_d0ec阅读 260评论 0 0
  • Book1:创建你的未来 [if !supportLists]1.[endif]效仿成功者 每到一个新的领域开始工...
    糊糊_87阅读 438评论 0 0
  • 宇宙人生万物万象,归纳起来就是六十四种情境,它是完整的系统。无论哪一种情境,对于我们来讲都是一个大的环境,而且在每...
    两木相撑阅读 190评论 0 2
  • xilingyan阅读 127评论 0 0