将PDF文件转换为字节数组的方法.(用于使用outputstream()进行清除)


  • 除了使用FileInputStreamtoByteArray(InputStream输入)之外,还有其他方法可以将文件(PDF)转换为字节数组吗
  • 有什么方法可以直接转换它吗。我在java.nio.file.*包中找到了Files.readAllBytes,但它在我的RAD中提供了ClassNotFoundException。我的系统中有java 8 JDK
  • java.nio.file.*包在java 8中不可用吗
  • 我的要求是不应该使用InputStram来流式传输文件

似乎是将文件的全部内容直接加载到内存中的byte[]中,然后将其写入OutputStream中。这种方法的问题是,如果在内存中完全加载1GB或2GB的文件,那么很快就会遇到OutOfMemoryError。为了避免这种情况,您应该以小块的形式从InputStream中读取数据,并将这些块写入输出流中。以下是文件下载的示例:

BufferedInputStream bis = new BufferedInputStream(
    new FileInputStream(new File("/path/to/folder", "file.pdf")));
ServletOutputStream outStream = response.getOutputStream();
//to make it easier to change to 8 or 16 KBs
//make some tests to determine the best performance for your case
int FILE_CHUNK_SIZE = 1024 * 4;
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = bis.read(chunk)) != -1) {
    outStream.write(chunk, 0, bytesRead);
}
bis.close();
outStream.flush();
outStream.close();

最新更新