2014-04-02 45 views
1

我要发文件,为OutputStream,的Java NegativeArraySizeException字节

所以我用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

嗯,这是一个相当危险的方式来读取文件。 Java中的int是32位整数,因此它驻留在范围-2147483648 - 2147483647中,而long是64位。

通常,您不应该一次读取整个文件,因为您的程序可能会耗尽大文件上的RAM。改为在FileReader之上使用BufferedReader

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();