共計(jì) 1599 個字符,預(yù)計(jì)需要花費(fèi) 4 分鐘才能閱讀完成。
要讀取 FTP 上的文件,您可以使用 Java 的 FTP 客戶端庫,如 Apache Commons Net 庫。以下是一個示例代碼,演示如何使用 Apache Commons Net 連接到 FTP 服務(wù)器并讀取文件:
-
首先,您需要在項(xiàng)目中導(dǎo)入 Apache Commons Net 庫。您可以從官方網(wǎng)站上下載并將其添加到項(xiàng)目的依賴項(xiàng)中。
-
接下來,您可以使用以下代碼連接到 FTP 服務(wù)器并讀取文件:
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FTPExample {public static void main(String[] args) {String server = "ftp.example.com";
int port = 21;
String username = "your-username";
String password = "your-password";
String remoteFile = "/path/to/remote-file.txt";
String localFile = "local-file.txt";
FTPClient ftpClient = new FTPClient();
try {ftpClient.connect(server, port);
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
OutputStream outputStream = new FileOutputStream(localFile);
boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
outputStream.close();
if (success) {System.out.println("File downloaded successfully.");
} else {System.out.println("File download failed.");
}
} catch (IOException e) {e.printStackTrace();
} finally {try {if (ftpClient.isConnected()) {ftpClient.logout();
ftpClient.disconnect();}
} catch (IOException e) {e.printStackTrace();
}
}
}
}
在上面的示例代碼中,您需要替換以下變量的值:
server:FTP 服務(wù)器的主機(jī)名或 IP 地址。port:FTP 服務(wù)器的端口號(通常為 21)。username:用于登錄的 FTP 用戶名。password:用于登錄的 FTP 密碼。remoteFile:要從 FTP 服務(wù)器讀取的遠(yuǎn)程文件的路徑。localFile:將遠(yuǎn)程文件保存到本地的路徑。
在代碼中,我們首先創(chuàng)建一個 FTPClient 對象,然后使用 connect 方法連接到 FTP 服務(wù)器。接下來,我們使用 login 方法進(jìn)行身份驗(yàn)證,并使用 enterLocalPassiveMode 方法進(jìn)入被動模式。然后,我們使用 setFileType 方法設(shè)置文件類型為二進(jìn)制。然后,我們創(chuàng)建一個 FileOutputStream 來保存下載的文件,并使用 retrieveFile 方法從 FTP 服務(wù)器下載文件。最后,我們使用 logout 和disconnect方法斷開與 FTP 服務(wù)器的連接。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!