Spring mvc 将长值存储在spring中的字节[]中
下面是代码片段: 我试图上传一个与数据类型一样长的文件,并将该文件大小存储在字节数组中Spring mvc 将长值存储在spring中的字节[]中,spring-mvc,file-upload,type-conversion,Spring Mvc,File Upload,Type Conversion,下面是代码片段: 我试图上传一个与数据类型一样长的文件,并将该文件大小存储在字节数组中 long fileSize = uploadedFile.getSize(); byte techGuide[] = new byte[fileSize]; 我得到了构建错误: 错误:不兼容的类型:可能存在从long到int的有损转换 请建议我缺少什么,我应该尝试什么 Path path = uploadedFile.toPath(); // File.toPath. 修复您的代码: // Not ne
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索引的限制。您需要将文件大小强制转换为int(并检查溢出)。但是,
Files.readAllBytes
会为您这样做,抛出一个OutOfMemoryError>Integer.MAX-8。仅代码的答案是低质量的答案。@TaslimOseni如果您是对的,您就是对的;补充