下面是代码片段:我正在尝试上传一个数据类型为long的文件,并将该文件大小存储在字节数组中。
long fileSize = uploadedFile.getSize();
byte techGuide[] = new byte[fileSize];
我得到了生成错误:错误:不兼容的类型:从long到int 的可能有损转换
请建议我缺少什么,我应该尝试什么?
Path path = uploadedFile.toPath(); // File.toPath.
修复您的代码:
// Not needed for readAllBytes.
long fileSize = Files.size(path);
if (fileSize > Integer.MAX) {
throw new IllegalArgumentException("File too large");
}
byte[] techGuide = new byte[(int)fileSize];
新代码:
byte[] techGuide = Files.readAllBytes(path);
数组受其int索引的限制。您需要将fileSize强制转换为int(并检查溢出(。然而,Files.readAllBytes
会为您执行此操作,抛出>的OutOfMemoryError;整数.MAX-8。