编程语言
首页 > 编程语言> > Java中RandomAccessFile的分块读取文件及分块写入

Java中RandomAccessFile的分块读取文件及分块写入

作者:互联网

先来了解下什么是RandomAccessFile:

Java随机流RandomAccessFile详细介绍及简单的应用_m0_57640408的博客-CSDN博客

下面对文件分块读写操作:

/**
 * RandomAccessFile练习,进行文件分块读写操作
 */
public class RandomAccessFileTest02 {
    public static void main(String[] args) {
        String sourcePath = "D:/TEST/test.zip";  //源原件
        String descpath = "D:/TEST/test2.zip";  //目标文件
        File sourceFile = new File(sourcePath);
        long fileLength = sourceFile.length();
        //每块文件的大小100M
        int blockSize = 1024*1024*100;
        int fileSize = (int) Math.ceil(fileLength *1.0 / blockSize);
        for(int i = 0;i<fileSize; i++){
            byte[] buff = randomRed(sourcePath, i);// 分段读取文件
            if(null!=buff){
                insert(descpath, i, buff);    //分段写入文件
            }
        }
    }

    /**
     * 分快读取
     *
     * @param path 文件路径
     * @param pointe 指针位置
     * @return byte[]
     */
    public static byte[] randomRed(String path, int pointe) {
        try {
            RandomAccessFile ra_read = new RandomAccessFile(path, "r");
            //获取RandomAccessFile对象文件指针的位置,初始位置是0
            ra_read.seek(pointe*1024*1024*100); // 移动文件指针位置,和每次读取文件的大小有关
            byte[] bytes = new byte[1024*1024*100]; //每次读取文件的大小
            int readSize = ra_read.read(bytes);
            if (readSize <= 0) {
                ra_read.close();
                return null;
            }
            //不足1024*1024*100需要拷贝去掉空字节
            if (readSize < 1024*1024*100) {
                byte[] copy = new byte[readSize];
                System.arraycopy(bytes, 0, copy, 0, readSize);
                return copy;
            }
            ra_read.close();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分块写入
     *
     * @param fileName 文件名
     * @param points 指针位置
     * @param data 插入内容
     */
    public static void insert(String fileName, long points, byte[] data) {
        try {
            File tmp = new File(fileName);
            RandomAccessFile randomAccessFile = new RandomAccessFile(tmp, "rw");
            randomAccessFile.seek(points*1024*1024*100);  //移动文件记录指针的位置,
            randomAccessFile.write(data);  //从start字节开始写数据
            randomAccessFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

标签:文件,Java,String,分块,int,RandomAccessFile
来源: https://blog.csdn.net/m0_57640408/article/details/120856712