我想用OutputStream发送文件,
所以我使用 byte[] = new byte[size of file ]
但我不知道我可以使用的最大尺寸是多少。
这是我的代码。
File file = new File(sourceFilePath);
if (file.isFile()) {
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
if(len>Integer.MAX_VALUE){
file_info.setstatu("Error");
}
else{
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent =new File_object();
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
fileEvent.setSender_name(file_info.getSender_name());
}
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
file_info.setstatu("Error");
}
} else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
file_info.setstatu("Error");
}
提前致谢。
最佳答案
出现异常的原因是这一行:
long len = (int) file.length();
从 long
到 int
的收缩转换可能会导致符号发生变化,因为高阶位被丢弃。参见 JLS Chapter 5, section 5.1.3 .相关引用:
A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.
你可以用一个简单的程序来测试它:
long a = Integer.MAX_VALUE + 1;
long b = (int) a;
System.out.println(b); # prints -2147483648
无论如何,您都不应该使用字节数组来读取内存中的整个文件,但要解决此问题,不要将文件长度转换为 int。然后您对下一行的检查将起作用:
long len = file.length();
关于以字节为单位的 Java NegativeArraySizeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800628/