java - 从服务器流式传输文件时,磁盘上的文件大小大于读取的总字节数,这是怎么回事?

标签 java file-io inputstream outputstream fileoutputstream

我正在从artifactory 读取一个二进制文件。根据artifactory,文件大小为34,952,058 字节,读取完成后记录的totalBytes 计数器也是34,952,058 字节。但磁盘上的文件大小为 39,426,048 字节。这是怎么回事?? 我尝试过 BufferedOutputStream、FileOutputStream 和 OutputStream。 每次都是一样的结果。我错过了什么?
这是我目前最新的代码:

try {
                URL url = new URL(fw.getArtifactoryUrl());
                URLConnection connection = url.openConnection();
                in = connection.getInputStream();
                File folder = utils.getFirmwareFolder(null, FirmwareUtils.FIRMWARE_LATEST, true);
                StringBuilder builder = new StringBuilder(folder.toString());
                builder.append("/").append(fw.getFileName());
                Path filePath = Paths.get(builder.toString());
                OutputStream out = Files.newOutputStream(filePath);

                int read = 0;
                int totalBytes = 0;

                while ((read = in.read(bytes)) > 0) {
                    totalBytes += read;
                    out.write(bytes);
                    out.flush();
                }
                logger.info("Total bytes read: " + totalBytes);
                in.close();
                out.close();

<<< more code >>>

最佳答案

您的代码读取正确,但写入错误

while ((read = in.read(bytes)) > 0) { // Read amount of bytes
    totalBytes += read;  // Add the correct amount of bytes read to total
    out.write(bytes);    // Write the whole array, no matter how much we read
    out.flush();         // Completely unnecessary, can harm performance
}

您需要 out.write(bytes, 0, read) 来仅写入您已读取的字节,而不是整个缓冲区。

关于java - 从服务器流式传输文件时,磁盘上的文件大小大于读取的总字节数,这是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50364323/

相关文章:

java - Long.toBinaryString 未返回 827.0 的预期二进制字符串

java - 当我对自引用实体进行查询时出现 SQLException

c++ - 一次将文件读入 vector

java - 数字格式中的空字符串

Java int 到带有特殊字符的 char

java - 显示文件夹中的歌曲到 jlist

java - 如何将xml解析为java对象?

java - 列出目录中与文件掩码(又名模式或 Glob)匹配的所有文件

Java:输入流标记限制

android - 使用 Json、Gson、InputStream 和 HttpPost 将文件插入 Mysql