JAVA NIO 读写文件

58 篇文章 0 订阅
	private static boolean write(byte[] data, String diskSrcPath, String fileName, String format) {
		File f = new File(diskSrcPath);
		if (!f.exists()) {
			f.mkdirs();
		}
		f = new File(diskSrcPath + "/" + fileName + "." + format);
		FileOutputStream fos = null;
		FileChannel fc = null;
		try {
			if (!f.exists()) {
				fos = new FileOutputStream(f);
				fc = fos.getChannel();
				ByteBuffer bb = ByteBuffer.allocate(data.length);
				bb.put(data);
				bb.flip();
				fc.write(bb);
				bb.clear();
				fc.close();
				fos.close();
				fc = null;
				fos = null;
				bb = null;
			}
		} catch (Exception e2) {
			log.error(e2);
		} finally {
			if (fc != null) {
				try {
					fc.close();
				} catch (IOException e) {
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}
		return true;
	}
// 这个是直接通过response流输出
private static void reader(HttpServletResponse response, String type, String path, String fileName) {
		File f = new File(type + path);
		if (!f.exists()) {
			RequestUtils.responseJSON(response, new Result(ResultCode.M404));
		} else {
			FileInputStream file = null;
			FileChannel fc = null;
			try {
				if (StringUtils.isNotBlank(fileName)) {
					response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
				}
				file = new FileInputStream(f);
				fc = file.getChannel();
				ByteBuffer b = ByteBuffer.allocate(2048);
				b.clear();
				while (fc.read(b) > 0) {
					response.getOutputStream().write(b.array());
					b.clear();
				}
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (Exception e) {
				log.error("输出文件异常", e);
				RequestUtils.responseJSON(response, new Result(ResultCode.M500).formatMsg(e.getMessage()));
			} finally {
				if (fc != null) {
					try {
						fc.close();
					} catch (IOException e) {
						log.error("输出文件异常", e);
					}
				}
				if (file != null) {
					try {
						file.close();
					} catch (IOException e) {
						log.error("输出文件异常", e);
					}
				}
			}
		}
	}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值