问题描述
我正在尝试将已下载的文件转换为 byte[] 并返回它。我可以在不失败的情况下转换的最大大小约为 70mb,这是我的 ubuntu 实例上的可用内存量。需要文件大小的 RAM 才能下载它是不现实的。
我已尝试将 BufferedInputStream 转换为 ByteArrayOutputStream,但它在开始写入时内存不足。在下面的代码中,它将在停止之前使其成为“开始缓冲写入”。
FileInputStream fis = null;
BufferedInputStream bis = null;
byte[] bytes = null;
byte[] buffer = new byte[1024];
int count = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
System.out.println("Starting buffered write");
while((count=bis.read(buffer)) != -1)
{
bos.write(buffer,count);
}
System.out.println("Finished buffered write");
//System.out.println("Trying copyLarge");
//IoUtils.copyLarge(fis,bos);
//System.out.println("Successful copyLarge");
System.out.println("Starting stream to bytes");
bytes = bos.toByteArray();
System.out.println("Finished stream to bytes");
fis.close();
bis.close();
bos.flush();
bos.close();
}
令我困惑的是,这种方法适用于大文件的上传功能没有问题。上传创建一个临时文件和一个输出流,然后将上传的文件输入流写入其中。有没有可能因为上传的临时文件在使用后没有被删除,它们正在消耗我的实例内存?
解决方法
正如 Kayaman 告诉我的那样,将文件作为字节数组加载需要内存中文件的完整大小。将我的文件作为 InputStreamResource 返回下载解决了我的问题,而没有字节数组。