使用Spring工具类拷贝流

以前我们拷贝输入输出流的时候,代码要写一大段,而且还需要手动关闭输入输出流,今天这里介绍一个非常好用且方便的工具类,Spring核心包自带的FileCopyUtils

  • FileCopyUtils.copy方法,将 InputStream 的数据拷贝到 OutputStream,并自动关闭输入输出流
	/**
	 * Copy the contents of the given InputStream to the given OutputStream.
	 * Closes both streams when done.
	 * @param in the stream to copy from
	 * @param out the stream to copy to
	 * @return the number of bytes copied
	 * @throws IOException in case of I/O errors
	 */
	public static int copy(InputStream in, OutputStream out) throws IOException {
		Assert.notNull(in, "No InputStream specified");
		Assert.notNull(out, "No OutputStream specified");

		try {
			return StreamUtils.copy(in, out);
		}
		finally {
			try {
				in.close();
			}
			catch (IOException ex) {
			}
			try {
				out.close();
			}
			catch (IOException ex) {
			}
		}
	}
  • 在这其中用到了StreamUtils工具类,StreamUtils.copy方法里的代码很像我们以前写的代码:
/**
	 * Copy the contents of the given InputStream to the given OutputStream.
	 * Leaves both streams open when done.
	 * @param in the InputStream to copy from
	 * @param out the OutputStream to copy to
	 * @return the number of bytes copied
	 * @throws IOException in case of I/O errors
	 */
	public static int copy(InputStream in, OutputStream out) throws IOException {
		Assert.notNull(in, "No InputStream specified");
		Assert.notNull(out, "No OutputStream specified");

		int byteCount = 0;
		byte[] buffer = new byte[BUFFER_SIZE];
		int bytesRead = -1;
		while ((bytesRead = in.read(buffer)) != -1) {
			out.write(buffer, 0, bytesRead);
			byteCount += bytesRead;
		}
		out.flush();
		return byteCount;
	}
  • 如果我们想将文件当作流返回前台,我们可以使用这个工具类
    @GetMapping("/getImage")
    @ResponseBody
    public void getImgByPath(String path, HttpServletResponse response) {
        if(StringUtils.isEmpty(path)){
           return;
        }
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        try {
            FileInputStream in = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            //Spring工具类, 拷贝输入流到输出流并自动关闭流资源
            FileCopyUtils.copy(in,out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值