简体   繁体   English

Java - 处理大文件

[英]Java - processing large files

I'm working on a spring mvc application. 我正在开发一个spring mvc应用程序。 at this time i need to have action for file downloading. 此时我需要对文件下载采取行动。 due to this post my controller's action now is like this: 由于这篇文章我的控制器的行动现在是这样的:

 @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
}

my problem is on the bytes declaration. 我的问题在于bytes声明。 file has a long getSize() method that return the size of the files. file有一个long getSize()方法,它返回文件的大小。 but i can't use byte[] bytes = new byte[file.getSize()]; 但我不能使用byte[] bytes = new byte[file.getSize()]; , because the array size must be an integer value. ,因为数组大小必须是整数值。 how can i solve this problem? 我怎么解决这个问题?

I don't want to copy whole file into memory. 我不想将整个文件复制到内存中。

Use IOUtils and just copy streams (file stream to response stream) 使用IOUtils并只复制流(文件流到响应流)

copy(InputStream input, OutputStream output)

Copies bytes from an InputStream to an OutputStream. 将字节从InputStream复制到OutputStream。

copy(InputStream input, OutputStream output, int bufferSize)

Copies bytes from an InputStream to an OutputStream using an internal buffer of the given size. 使用给定大小的内部缓冲区将InputStream中的字节复制到OutputStream。

Read your data in a loop with a buffer of bytes. 使用字节缓冲区在循环中读取数据。 Reading to large byte arrays could be a performance issue. 读取大字节数组可能是性能问题。

If you need to save the data use a file or stream. 如果需要保存数据,请使用文件或流。

Reading a binary input stream into a single byte array in Java 在Java中将二进制输入流读入单个字节数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM