码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-08-18 19:53:50      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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

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 文件,意外地发现居然子文件都是有效的,所以说音频文件的数据存储方式和图片以及视频文件不一样么...

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

标签:

原文地址:http://www.cnblogs.com/xmcx1995/p/5785018.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!