Java FTP服務器(例如Apache Commons Net庫)允許您通過FTP協議下載文件。以下是一個簡單的示例,說明如何使用Java從FTP服務器下載文件:
首先,確保已將Apache Commons Net庫添加到項目依賴項中。如果您使用Maven,可以在pom.xml文件中添加以下依賴項:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
接下來,編寫一個Java程序來下載文件:
import org.apache.commons.net.ftp.FTPClient;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FTPDownloadExample {
public static void main(String[] args) {
String server = "ftp.example.com"; // FTP服務器地址
int port = 21; // FTP端口(通常為21)
String user = "username"; // FTP用戶名
String pass = "password"; // FTP密碼
FTPClient ftpClient = new FTPClient();
try {
// 連接到FTP服務器
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
// 設置文件類型為二進制,以防止文件損壞
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 要下載的文件名
String remoteFileName = "remote-file.txt";
// 本地保存文件的路徑
String localFileName = "local-file.txt";
// 從FTP服務器下載文件
try (BufferedInputStream inputStream = new BufferedInputStream(ftpClient.retrieveFileStream(remoteFileName));
FileOutputStream outputStream = new FileOutputStream(localFileName)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
System.out.println("文件下載成功: " + localFileName);
} catch (IOException ex) {
System.out.println("Error downloading file: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
// 斷開與FTP服務器的連接
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
在這個示例中,我們首先創建一個FTPClient
對象,然后連接到FTP服務器并登錄。接著,我們設置文件類型為二進制,以防止在下載過程中損壞文件。然后,我們使用retrieveFileStream()
方法獲取文件的輸入流,并將其寫入到本地文件中。最后,我們斷開與FTP服務器的連接。
請注意,您需要根據實際情況替換示例中的服務器地址、端口、用戶名、密碼和文件名。