原为地址:https://www.toymoban.com/diary/java/363.html
在Java应用程序中实现FTP功能需要使用FTPClient类和相关方法。下面是实现三个主要功能的示例代码:
void ftpList_actionPerformed(ActionEvent e) { String server = serverEdit.getText(); String user = userEdit.getText(); String password = passwordEdit.getText(); String path = pathEdit.getText(); try { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server); ftpClient.login(user, password); if (path.length() != 0) ftpClient.changeWorkingDirectory(path); FTPFile[] files = ftpClient.listFiles(); for (FTPFile file : files) { System.out.println(file.getName()); } ftpClient.logout(); ftpClient.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } }
void getButton_actionPerformed(ActionEvent e) { String server = serverEdit.getText(); String user = userEdit.getText(); String password = passwordEdit.getText(); String path = pathEdit.getText(); String filename = filenameEdit.getText(); try { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server); ftpClient.login(user, password); if (path.length() != 0) ftpClient.changeWorkingDirectory(path); FileOutputStream outputStream = new FileOutputStream(new File(filename)); ftpClient.retrieveFile(filename, outputStream); outputStream.close(); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } }
void putButton_actionPerformed(ActionEvent e) { String server = serverEdit.getText(); String user = userEdit.getText(); String password = passwordEdit.getText(); String path = pathEdit.getText(); String filename = filenameEdit.getText(); try { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server); ftpClient.login(user, password); if (path.length() != 0) ftpClient.changeWorkingDirectory(path); FileInputStream inputStream = new FileInputStream(new File(filename)); ftpClient.storeFile(filename, inputStream); inputStream.close(); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } }
请注意,以上示例代码使用的是Apache Commons Net库中的FTPClient类。您需要确保已将相关库文件添加到项目中,并在代码中进行引入。此外,根据您的需求和环境设置,可能需要进行适当的异常处理和其他调整。