用RandomAccessFile分割输出文件

一般上传大文件的时候,就需要把文件分割几部分后再上传,那么久需要用到RandomAccessFile方法,思路如下:
先判断需要分割的次数,再把文件分割读取之后,再用FileOutputStream方法把读取后的部分输出到其他文件。

public static void main(String[] args) {
		// 定义读取的文件
		String src = "d:/readme.txt";
		// 定义输出文件夹
		String base = "d:/data/";
		// 判断文件后缀名(.txt)
		String substring = src.substring(src.lastIndexOf("."));
		// 每次读10个字节
		int block = 10;
		// 获取文件内容的长度
		long length = new File(src).length();
		// 分割文件的数量
		int times = (int) Math.ceil(length / (float) block);
		// 定义每次执行3个线程
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		// 创建输出的文件夹
		new File(base).mkdirs();
		// 循环分割文件
		for (int i = 0; i < times; i++) {
			final int j = i;
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					try {
						// 用RandomAccessFile读取文件
						RandomAccessFile in = new RandomAccessFile(src, "r");
						// 每次读取从j*block开始
						in.seek(j * block);
						// 读取block个字节
						byte[] box = new byte[block];
						// 把文件读取放到size
						int read = in.read(box);
						// 定义分割后的文件名
						String fileName = UUID.randomUUID().toString();
						// 用FileOutputStream创建文件,拼接路径
						FileOutputStream out = new FileOutputStream(base + fileName + substring);
						// 用write方法写入size个字节
						System.out.println(box);
						// write方法写入字节,box是长度,从0开始,把read
						out.write(box, 0, read);
						// 关闭流
						out.close();
						in.close();
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
					}
				}
			});
		}
		threadPool.shutdown();
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值