文件分割

以下是代码
将一个文件以MB为单位进行分割,分割后的小文件存储在一个文件夹下,分割后文件以.temp为命名,如 file.txt 文件分割后为 file0.tmp file1.temp file2.temp 等


package com.syt.blue0807.work;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Subject01 {
	/**
	 * 
	 * @author blue
	 * 
	 * @date 2020年8月7日
	 * 
	 */
	public static void main(String[] args) {
		//		源路径 	每份大小/m 		输出路径
		split("E:\\test.JPG", 4, "E:\\");
	}
	public static void split(String src, int cutcount, String outpath) {
		BufferedInputStream bf = null;
		BufferedOutputStream of = null;
		byte[] b = new byte[1024 * 1024];
		File file = new File(src);
		long srcSize = file.length();
		long cutSize = 1024 * 1024 * cutcount;
		int filecount = (int) (srcSize / cutSize);
		try {
			bf = new BufferedInputStream(new FileInputStream(src));
			int len = -1;
			for (int i = 0; i < filecount; i++) {
				String splitname = file.getName().substring(0, file.getName().lastIndexOf(".")) + i + ".tmp";
				of = new BufferedOutputStream(new FileOutputStream(outpath + splitname));
				int count = 0;
				try {
					while ((len = bf.read(b)) != -1) {
						of.write(b, 0, len);
						count += len;
						of.flush();
						if (count > cutSize) {
							break;
						}
					}

				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
			
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {
			try {
				
				if(of!=null) {
					of.close();		
				}
				if(bf!=null){
					bf.close();
				}
				System.out.println("分割完成");
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值