用java实现一个大文件分片方法

描述:工作中需要将大文件分片后,上传到阿里oss,分片方法实现如下

  /**
     * 文件分片方法
     * 
     * @param file       文件对象
     * @param sliceIndex  第几片,从1开始
     * @param sliceSize   每片大小(byte)
     * @return 字节数组
     */
    public static byte[] sliceFile(File file, int sliceIndex, int sliceSize) {
        RandomAccessFile arf = null;
        try {
            arf = new RandomAccessFile(file, "r");
            long fileLength = file.length();
            int numSlices = (int) Math.ceil((double) fileLength / sliceSize);
            //限制参数越界
            if (sliceIndex <= 0 || sliceIndex > numSlices) {    
                return null;
            }
            int sliceLength = (int) Math.min(sliceSize, fileLength - (long) (sliceIndex - 1) * sliceSize);
            byte[] data = new byte[sliceLength];
            arf.seek((long) (sliceIndex - 1) * sliceSize);
            arf.readFully(data);
            return data;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(arf != null) {
                try {
                    arf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


总结

      该方法使用文件随机访问类(RandomAccessFile)提高了文件的读取速度,在关键位置使用long定义变量,可以支持超过1个G的大文件