我正在开发一个 spring mvc 应用程序。在这个时候我需要有文件下载的 Action 。由于this post我的 Controller 现在的 Action 是这样的:
@RequestMapping(value = "/file/{id}", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void getFile(@PathVariable("id") int id, HttpServletResponse response) throws FileNotFoundException {
//fetch file record from database
Files file = orchService.fileFind(id);
//directory of the file is based on file ID(this is not important in this question)
InputStream inputStream = new FileInputStream(myFileDirectory);
response.setHeader("Content-Disposition", "attachment; filename=\"filename " + file.getId() + "."+file.getExtension()+"\"");
int read=0;
byte[] bytes = new byte[];
//remaining of code
}
我的问题出在 bytes
声明上。 file
有一个返回文件大小的 long getSize()
方法。但我不能使用 byte[] bytes = new byte[file.getSize()];
,因为数组大小必须是整数值。我该如何解决这个问题?
我不想将整个文件复制到内存中。
最佳答案
使用IOUtils并且只复制流(文件流到响应流)
copy(InputStream input, OutputStream output)
将字节从 InputStream 复制到 OutputStream。
copy(InputStream input, OutputStream output, int bufferSize)
使用给定大小的内部缓冲区将字节从 InputStream 复制到 OutputStream。
关于Java - 处理大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27873899/