以前我们拷贝输入输出流的时候,代码要写一大段,而且还需要手动关闭输入输出流,今天这里介绍一个非常好用且方便的工具类,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();
}
}