我想用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");
}
提前致谢。
答案 0 :(得分:3)
您获得例外的原因是由于这一行:
long len = (int) file.length();
从long
到int
的缩小转换可能会导致符号发生变化,因为丢弃了更高阶的位。见JLS Chapter 5, section 5.1.3。相关引用:
有符号整数到整数类型T的缩小转换只会丢弃除n个最低位之外的所有位,其中n是用于表示类型T的位数。除了可能丢失有关幅度的信息之外数值,这可能导致结果值的符号与输入值的符号不同。
您可以使用简单的程序对此进行测试:
long a = Integer.MAX_VALUE + 1;
long b = (int) a;
System.out.println(b); # prints -2147483648
你不应该使用字节数组来读取内存中的整个文件,但为了解决这个问题,不要将文件长度转换为int。然后检查下一行将起作用:
long len = file.length();
答案 1 :(得分:0)
嗯,这是一种非常危险的文件阅读方式。 Java中的int
是32位int,因此它位于-2147483648 - 2147483647范围内,而long
是64位。
通常,您不应该立即读取整个文件,因为您的程序可能会耗尽大文件的RAM。请改用BufferedReader上的FileReader代替。