大文件分片上传RandomAccessFile类测试

将文件拆成多个小的分片文件,再将这些小文件合并恢复成原来的大文件,通常的方式就是使用FileOutputStream按照顺序append,如果采用多线程合并会导致文件错乱。java1.0的RandomAccessFile类把文件看成一个巨大的字节数组,seek方法能指定任意的数组位置,相当于一个游标,通过这个类的相关api能够实现分片文件的任意先后顺序合并

public static void main(String[] args) throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile(new File("C:\\Users\\jizhang\\Desktop\\test\\RandomAccessFileTest.txt"), "rw");
        byte[] contentBytes = "设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。".getBytes();
        int shardSize = 10;
        int shardTotal = (contentBytes.length + shardSize - 1) / shardSize;
        byte[][] tempData = new byte[shardTotal][shardSize];
        for (int i = 0; i < shardTotal; i++) {
            int begin = i * shardSize;
            int end = Math.min((begin + shardSize), contentBytes.length);
            tempData[i] = Arrays.copyOfRange(contentBytes, begin, end);
        }

        List<Integer> seqList = new ArrayList<>();
        for (int i = 0; i < tempData.length; i++) {
            seqList.add(i);
        }
        Collections.shuffle(seqList);
        System.out.println("seqList = " + seqList);

        for (Integer index : seqList) {
            randomAccessFile.seek(index * shardSize);
            randomAccessFile.write(tempData[index]);
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值