使用 java I/O 实现一个简易的文件分割器功能

import java.io.*;
import java.util.Scanner;

import static java.awt.Desktop.getDesktop;

public class IOSplit {
    public static void main(String[] args) throws IOException {
        /**
         * 对文件进行分割:
         * 1.首先,先通过调用File的方法去确定文件是否存在(.exists()),以及
         * 获得文件的大小(字节:.length())。
         * 2.找到文件后,将文件存入数组中(.read(byte[] b))
         * 3.通过输入需要分隔的大小将文件循环(for)写入新的文件中(.write(byte[] b, int off, int len))
         * byte[] b : 字节数组
         * int off  : 从byte[] b的下标为off的元素开始写入
         * int len  : 写入的长度
         */
        Scanner in = new Scanner(System.in);
        //文件
        File file;
        //文件路径
        String path = null;
        //判断文件是否存在
        do {
            System.out.println("请输入文件路径:");
            path = in.next();
            file = new File(path);
            if (!file.exists()){
                System.out.println("文件不存在!");
            }
        } while (!file.exists());
        //获取文件的字节长度
        int length = (int)file.length();
        System.out.print("文件大小:" + file.length());
        System.out.println("请输入文件分割的大小:(单位byte)");
        int splitByte = in.nextInt();
        System.out.println("开始分割.....");
        //读取文件到字节数组中
        FileInputStream fileInputStream = new FileInputStream(path);
        byte[] inBuffer = new byte[length];
        fileInputStream.read(inBuffer);
        fileInputStream.close();
        //通过for循环分割文档
        for (int i = 1; length > 0; i++) {
            //输出文件路径path,并在末尾添加编号i
            FileOutputStream fileOutputStream = new FileOutputStream(path + i);
            //为防止数组下标越界,当剩余长度小于分割长度时,分割长度为length
            if (length > splitByte){
                //splitByte * (i - 1)从0开始,每隔splitByte分割一次,长度为splitByte
                fileOutputStream.write(inBuffer,splitByte * (i - 1),splitByte);
            }else{
                fileOutputStream.write(inBuffer,splitByte * (i - 1),length);
            }
            //分割后长度  -  splitByte
            length = length - splitByte;
            System.out.println(path + i);
            fileOutputStream.close();
        }
        System.out.println("分隔完毕!");
        //打开输入文件夹
        StringBuffer cPath = new StringBuffer(path);
        String newPath = cPath.substring(0,cPath.lastIndexOf("\\"));
        getDesktop().open(new File(newPath));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值