Java - 处理大文件

时间:2015-01-10 07:29:17

标签: java arrays file spring-mvc

我正在使用spring mvc应用程序。此时我需要对文件下载采取行动。由于this post我的控制器现在的动作是这样的:

 @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()];,因为数组大小必须是整数值。我该如何解决这个问题?

我不想将整个文件复制到内存中。

2 个答案:

答案 0 :(得分:2)

使用IOUtils并只复制流(文件流到响应流)

copy(InputStream input, OutputStream output)

将InputStream中的字节复制到OutputStream。

copy(InputStream input, OutputStream output, int bufferSize)

使用给定大小的内部缓冲区将InputStream中的字节复制到OutputStream。

答案 1 :(得分:1)

使用字节缓冲区在循环中读取数据。读取大字节数组可能是性能问题。

如果您需要保存数据,请使用文件或流。

Reading a binary input stream into a single byte array in Java