我正在从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/