Java-->利用文件指针分割文件

--> 大体上和字节流分割的方式没什么区别,只是加入文件指针确定要开始分割的位置...

package com.dragon.java.splitmp3;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要分割的文件路径:");
        String filePath = scanner.next();
        File srcFile = new File(filePath);
        System.out.println("请输入要分割的份数:");
        int n = scanner.nextInt();

        long pointer = 0;
        // 分成 n 段,每段的长度,加 1 为防止数据丢失
        long parentLength = srcFile.length() / n + 1;
        RandomAccessFile rafSrc = new RandomAccessFile(srcFile, "r");
        for (int i = 1; i < n + 1; i++) {
            // 分割的子文件的名字
            RandomAccessFile rafDec = new RandomAccessFile(new File(
                    srcFile.getParent(), "part" + i + "."
                            + srcFile.getName().split("\\.")[1]), "rw");

            // 将文件指针 指向上次分割完成时的指针位置
            rafSrc.seek(pointer);

            byte[] buffer = new byte[(int) parentLength];
            int len = rafSrc.read(buffer);
            rafDec.write(buffer, 0, len);
            pointer = rafSrc.getFilePointer();

        }
    }
}

--> 这次分割了一个mp3 文件,意外地发现居然子文件都是有效的,所以说音频文件的数据存储方式和图片以及视频文件不一样么...

posted on 2016-08-18 18:36  西门吃雪  阅读(496)  评论(0编辑  收藏  举报

导航