分割文件,把大的文件分割成小的文件,并且新建一个文件夹用于存放小的文件...

本文介绍了一个实用的文件分割工具,能够将大文件按照指定大小分割成多个小文件,并保持数据的完整性。该工具通过逐行读取原始文件的方式,确保了分割后的小文件能够正确地按序号排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



/**
     * 把文件按照设置的大小分割成多个小的文件,解析后的多个文件,是在原文件后加上序号
     * 
     * @param fileName 原始的文件
     * @param size 分割后每个文件的大小,有可能大于这个值,
     * 因为在解析的时候,是读取原始文件的一行进行解析的
     * @throws IOException
     */



    public static void splitFile(String fileName, int size) throws IOException
    {
        File file = new File(fileName);
        if (!file.exists() || !file.canRead())
        {
            System.out.println("file not exist");
            return;
        }
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String str = br.readLine();
        String path = fileName.substring(0, fileName.lastIndexOf("\\") + 1);
        String newPath = fileName.substring(0, fileName.lastIndexOf("."));
        File filePath = new File(newPath);
        if (!filePath.exists())
        {
            filePath.mkdir();
        }
        path = newPath + "\\";
        String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
                fileName.lastIndexOf("."));
        int count = 1;
        
        File fileW = new File(path + name + count + ".txt");
        if (!fileW.exists())
        {
            fileW.createNewFile();
        }
        FileWriter fw = new FileWriter(fileW);
        BufferedWriter bw = new BufferedWriter(fw);
        int fileSize = 0;
        // System.out.println("name : " + name + " path : " + path) ;
        while (null != str)
        {
            if (fileSize >= size)
            {
                // 重新生成小的文件
                bw.close();
                fw.close();
                count += 1;
                fileW = new File(path + name + count + ".txt");
                if (!fileW.exists())
                {
                    fileW.createNewFile();
                }
                fw = new FileWriter(fileW);
                bw = new BufferedWriter(fw);
                fileSize = 0;
            }
            fileSize += str.getBytes().length;
            bw.write(str + "\n");
            str = br.readLine();
        }
        bw.close();
        fw.close();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值