从服务器流式传输文件时,磁盘上的文件大小大于读取的总字节数,这是怎么回事?
When streaming a file from a server, the file size on disk is bigger than the total bytes read, what's going on?
我正在从 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)
只写入您读取的字节而不是整个缓冲区。
我正在从 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)
只写入您读取的字节而不是整个缓冲区。