分割文件,把文件分割成制定大小的多个子文件

/**
     * 把文件按照设置的大小分割成多个小的文件,解析后的多个文件,是在原文件后加上序号
     * 
     * @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 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();
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值