我正在使用Java中的FTPClient從服務器下載文件。當文件被下載時,我想檢查它的完整性,然後刪除它。 我這樣做是通過比較下載的文件(以字節爲單位)和服務器上的文件(以字節爲單位)的大小來實現的,但結果與預期不符。我從FTP服務器下載的文件長度與服務器上的文件長度不相同
下面是從我的傳輸目錄的摘錄:
for (int i = 0; i <= insideDirectory.length - 1; i++) {
FTPFile transferFile = insideDirectory[i];
LOGGER.info("Passing file" + folder.getName() + "/" + transferFile.getName());
File downloadFile = new File("https://stackoverflow.com/users/home/example" + i + ".mp4");
OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile));
System.out.println(transferFile.getSize());
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
InputStream inputStream = ftpClient
.retrieveFileStream(folder.getName() + "/" + transferFile.getName());
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream2.write(bytesArray, 0, bytesRead);
}
Boolean success = ftpClient.completePendingCommand();
if (success) {
System.out.println("File #" + i + " has been downloaded successfully.");
checkIfExists(downloadFile, transferFile);
}
下面是我checkIfExists
方法
public void checkIfExists(File downloadedFile, FTPFile remoteFileToDelete) {
Long downloadedLength = downloadedFile.length();
Long remoteLength = remoteFileToDelete.getSize();
if (downloadedFile.length() == remoteFileToDelete.getSize()) {
LOGGER.info(downloadedLength + "exists and is the same length as " + remoteLength + ". Let's delete");
} else {
LOGGER.info(downloadedLength + "is not the same length as " + remoteLength + ". Let's not delete");
}
}
這裏是輸出運行循環兩次之後,你可以看到,大小下載的文件可能有所不同:
File #0 has been downloaded successfully.
INFO: 7596008is not the same length as 7600840. Let's not delete
File #1 has been downloaded successfully.
INFO: 6873664is not the same length as 6878544. Let's not delete
File #2 has been downloaded successfully.
INFO: 7558112is not the same length as 7564744. Let's not delete
File #3 has been downloaded successfully.
INFO: 8662336is not the same length as 8665108. Let's not delete
File #0 has been downloaded successfully.
INFO: 7594312is not the same length as 7600840. Let's not delete
File #1 has been downloaded successfully.
INFO: 6870392is not the same length as 6878544. Let's not delete
File #2 has been downloaded successfully.
INFO: 7559184is not the same length as 7564744. Let's not delete
File #3 has been downloaded successfully.
INFO: 8660888is not the same length as 8665108. Let's not delete
我該如何檢查? – steam1234322
底部的輸出是否不夠?它比較兩個文件的字節大小 – steam1234322
啊,我明白了。然後Alnitak發現了它。 –