—
一、FTP連接
FTPClient類中最基本的方法就是連接FTP服務器,可以通過FTPClient對象的connect(String hostname)
方法進行連接,該方法的參數為FTP服務器的主機名。在連接成功後,可通過login(String username, String password)
方法進行登錄驗證,其中username和password分別為FTP服務器的用戶名和密碼。
FTPClient ftpClient = new FTPClient(); ftpClient.connect("ftp.example.com"); ftpClient.login("username", "password");
FTPClient還提供了enterLocalPassiveMode()
方法,用於設置客戶端在傳輸數據時使用被動模式傳輸(passive mode),該方法一般在登錄成功後調用。
ftpClient.enterLocalPassiveMode();
二、上傳和下載
通過FTPClient對象的storeFile(String remote, InputStream local)
方法可以將本地的文件上傳至FTP服務器中,參數remote為上傳至FTP服務器的文件路徑,local為本地文件的輸入流。
File file = new File("local_file_path"); InputStream inputStream = new FileInputStream(file); ftpClient.storeFile("remote_file_path", inputStream); inputStream.close();
FTPClient還提供了retrieveFile(String remote, OutputStream local)
方法,可用於將FTP服務器中的文件下載到本地,其中remote為FTP服務器中的文件路徑,local為下載文件的輸出流。
File file = new File("local_file_path"); OutputStream outputStream = new FileOutputStream(file); ftpClient.retrieveFile("remote_file_path", outputStream); outputStream.close();
三、文件列表操作
FTPClient還提供了文件列表操作的方法,包括listFiles(String pathname)
用於列出FTP服務器某一路徑下的所有文件和目錄,其中pathname為要列出的FTP服務器路徑,返回值為FTPFile數組。
FTPFile[] files = ftpClient.listFiles("server_path"); for (FTPFile file : files) { if (file.isFile()) { System.out.println(file.getName() + " is a file."); } else if (file.isDirectory()) { System.out.println(file.getName() + " is a directory."); } }
該類還提供了makeDirectory(String pathname)
和removeDirectory(String pathname)
方法,用於在FTP服務器上創建和刪除目錄,其中pathname為要操作的FTP服務器路徑。
ftpClient.makeDirectory("new_directory"); ftpClient.removeDirectory("existing_directory");
四、異常處理
在使用FTPClient類時,需要注意異常處理。FTPClient類中提供了FTPConnectionClosedException、SocketException、IOException等異常的處理方法,可通過try-catch語句進行捕獲。
try { ftpClient.storeFile("remote_file_path", inputStream); inputStream.close(); } catch (FTPConnectionClosedException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/153766.html