Java怎样提升上传文件速度

1、将传统的IO流改为NIO

/**
	 *
	 * Title: upload
	 * Description: 上传文件
	 * @param file
	 * @param licenseType
	 * @param realName
	 * @see IOcrUploadFileService#upload(MultipartFile, String, String)
	 */
	@Override
	@Transactional
	public Long upload(MultipartFile file, String licenseType, String realName) {
		checkFile(file, licenseType);
		// 写入数据库
		String fileName = file.getOriginalFilename();
		String zipNameSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		String zipName = fileName.substring(0, fileName.lastIndexOf("."));
		Long id = ocrUploadFileDao.save(licenseType.trim(), zipName, zipNameSuffix, realName);
		FileInputStream in = null;
		FileOutputStream out = null;
		FileChannel inChannel = null;
		FileChannel outChannel = null;
		try {
			in = (FileInputStream) file.getInputStream();
			// 创建目录
			File rootFile = new File(rootDirectory);
			if (!rootFile.exists()) {// 如果文件夹不存在
				rootFile.mkdir();// 创建文件夹
			}
			File zipFile = new File(rootFile, fileName);
			out = new FileOutputStream(zipFile);
			inChannel = in.getChannel();
			outChannel = out.getChannel();
			// 分配指定大小缓存区
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			// 将通道中的数据缓冲区中
			while (inChannel.read(buffer) != -1) {
				buffer.flip();// 切换成读数据模式
				// 将缓冲区中的数据写入通道中
				outChannel.write(buffer);
				buffer.clear();// 清空缓冲区
			}
		} catch (IOException e) {
			logger.error("uploadFile has error:{}", e);
			throw new BusinessException(10005, "上传文件异常");
		} finally {
			try {
				if (outChannel != null) {
					outChannel.close();
				}
				if (out != null) {
					out.close();
				}
				if (inChannel != null) {
					inChannel.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return id;
	}

2、如果上传文件过大,导致内存溢出,那么就需要修改JVM参数:Xmx(JVM最大的堆内存大小)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值