是否有更好的方法将文件的全部内容写入OutputStream? [英] Is there a better way to write the full contents of a file to an OutputStream?
问题描述
当我想将文件的全部内容写入OutputStream
时,我通常将缓冲区分配为byte[]
,然后进行for
循环以将文件InputStream
中的read
数据写入缓冲区,并将缓冲区内容写入OutputStream
,直到InputStream
没有更多字节可用.
When I want to write the full contents of a file into an OutputStream
, I usually allocate a buffer as a byte[]
, then make a for
loop to read
data from the file's InputStream
into the buffer and write the buffer contents into the OutputStream
, until the InputStream
has no more bytes available.
对我来说,这似乎很笨拙.有更好的方法吗?
This seems rather clumsy to me. Is there a better way to do this?
此外,我始终不确定缓冲区的大小.通常,我分配1024个字节,因为感觉很好.有没有更好的方法来确定合理的缓冲区大小?
Also, I am always unsure about the buffer size. Usually, I am allocating 1024 bytes, because it just feels good. Is there a better way to determine a reasonable buffer size?
在当前情况下,我想将文件的全部内容复制到写入HTTP响应内容的输出流中.因此,这不是关于如何在文件系统上复制文件的问题.
In my current case, I want to copy the full contents of a file into the output stream that writes the contents of an HTTP response. So, this is not a question about how to copy files on the file system.
推荐答案
For Java 1.7+ you can use the Files.copy(Path, OutputStream), e.g.
HttpServletResponse response = // ...
File toBeCopied = // ...
try (OutputStream out = response.getOutputStream()) {
Path path = toBeCopied.toPath();
Files.copy(path, out);
out.flush();
} catch (IOException e) {
// handle exception
}
注意,由于您正在处理HttpServletResponse
也是设置正确响应头的好主意.在将实际文件数据复制到响应之前,在 之前添加以下行:
Note, since you are dealing with HttpServletResponse
is is also a good idea to set correct response headers. Add the following lines before you copy the actual file data to the response:
String mimeType = URLConnection.guessContentTypeFromName(toBeCopied.getName());
String contentDisposition = String.format("attachment; filename=%s", toBeCopied.getName());
int fileSize = Long.valueOf(toBeCopied.length()).intValue();
response.setContentType(mimeType);
response.setHeader("Content-Disposition", contentDisposition);
response.setContentLength(fileSize);
Note, the encoding of the file name passed to the content disposition is important, see this question.
这篇关于是否有更好的方法将文件的全部内容写入OutputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!