如果使用的是Apache Commons FTPClient类来从FTP服务器下载文件,可能会遇到该问题。此问题由于默认情况下FTPClient使用ASCII模式而不是二进制模式加载数据而导致。
下面是一个解决该问题的示例代码:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPDownloader {
public static void main(String[] args) {
String server = "your_ftp_server_address";
int port = 21;
String user = "username";
String pass = "password";
String remoteFilePath = "/path/on/server/file.txt";
String localFilePath = "/path/on/local/machine/file.txt";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileOutputStream outputStream = new FileOutputStream(localFilePath);
InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream.write(bytesArray, 0, bytesRead);
}
boolean complete = ftpClient.completePendingCommand();
if (complete) {
System.out.println("File has been downloaded successfully.");
}
inputStream.close();
outputStream.close();
} catch (IOException ex) {
System.out.println("Error while downloading file: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
这个示例代码使用二进制文件类型从FTP服务器下载文件,确保获取源文件中的所有字节。此外,在读取数据时,代码使用字节数组缓冲器将数据保存在内存中,由于此过程中的连续