【问题标题】:Java NegativeArraySizeException in byte字节中的 Java NegativeArraySizeException
【发布时间】:2014-04-02 02:51:45
【问题描述】:

我想用 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");
        }

提前致谢。

【问题讨论】:

    标签: java file bytearray max-size


    【解决方案1】:

    您收到异常的原因是由于这一行:

    long len = (int) file.length();
    

    longint 的缩小转换可能会导致符号发生变化,因为丢弃了更高的位。见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();
    

    【讨论】:

      【解决方案2】:

      嗯,这是一种非常危险的文件读取方式。 Java 中的int 是 32 位 int,因此它位于 -2147483648 - 2147483647 范围内,而 long 是 64 位。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-03
        • 1970-01-01
        • 2013-01-22
        • 1970-01-01
        相关资源
        最近更新 更多