以字节为单位的 Java NegativeArraySizeException

标签 java file arrays max-size

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

longint 的收缩转换可能会导致符号发生变化,因为高阶位被丢弃。参见 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/

相关文章:

java - ImageView,为什么大小不同?

Java:将 JComponents 添加到具有静态大小和定位的 JPanel

java - 下载 Maven 依赖项时校验和验证失败

java - 如何将所有输出打印到txt文件

java - 如何将页面调用的内容保存到jsp/java中的文件中?

php - 我如何在 Joomla 2.5 virutemart 上显示购物车中的商品数量?

java - 在 Spring Integration 中为 Redis 创建 MessageSource

java - 将 CSV 文件转换为 XLS 时出现问题

android - 以天为键的 JSONObject 到 JSONArray

java - 如何将 String.split 与文本文件一起使用以添加到简单数组