文件分片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013160017/article/details/78124848

文件分片

package com.chow;

import java.io.*;
import java.nio.ByteBuffer;

/**
 * Created by zhouhaiming on 2017-7-31 14:35
 * Email: [email protected]
 *
 * @Description:
 */
public class MultipartUploadSender {

    public static void main(String[] args) {
        MultipartUploadSender test = new MultipartUploadSender();
        test.randomRed("E:\\共享文件夹\\test.doc");


    }

    /**
     * 文件分片
     *
     * @param path 文件路径
     **/
    /**
     * model各个参数详解
     * r 代表以只读方式打开指定文件
     * rw 以读写方式打开指定文件
     * rws 读写方式打开,并对内容或元数据都同步写入底层存储设备
     * rwd 读写方式打开,对文件内容的更新同步更新至底层存储设备
     *
     * **/
    public void randomRed(String path) {
        try {
            File file = new File(path);
            System.out.println("文件长度:" + file.length());
            long fileLength = file.length();
            long multipartSize = 2 * 1024 * 1024;//文件被切割的大小:2M
            double total = (double) fileLength / multipartSize;//每个文件分的片数。
            int num = (int) Math.ceil(total); //如果小数点大于1,整数加一 例如4.1 =》5
            long pointe = 0;
            InputStream inputStream;
            for (int i = 1; i <= num; i++) {
                RandomAccessFile raf = new RandomAccessFile(file, "r");
                //获取RandomAccessFile对象文件指针的位置,初始位置是0
                raf.seek(pointe);//移动文件指针位置,pointe是跳过的长度
                byte[] buff = new byte[(int) multipartSize];//每次读取200M的大小
                int byteCount = 0;
                if ((byteCount = raf.read(buff)) > 0) {
                    inputStream = new ByteArrayInputStream(buff, 0, byteCount);
                    //打印读取的内容,并将字节转为字符串输入
                    String a = new String(buff, 0, byteCount);
                    System.out.println(a + "\t长度:" + a.length());
//                    String fileName="E:\\共享文件夹\\test\\"+i+".txt";
                    String fileName = "E:\\共享文件夹\\test\\" + i;
                    FileOutputStream fileOutputStream = new FileOutputStream(fileName);
                    int ch = 0;
                    byte[] bytes = new byte[1024];
                    while ((ch = inputStream.read(bytes)) > 0) {
                        fileOutputStream.write(bytes, 0, ch);
                    }
                    fileOutputStream.close();
                    inputStream.close();
                }
                pointe = pointe + multipartSize;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u013160017/article/details/78124848