在Java应用程序中实现FTP功能需要使用FTPClient类和相关方法。下面是实现三个主要功能的示例代码:
1)显示FTP服务器上的文件:
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(); } }
2)从FTP服务器下载一个文件:
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(); } }
3)向FTP服务器上传一个文件:
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类。您需要确保已将相关库文件添加到项目中,并在代码中进行引入。此外,根据您的需求和环境设置,可能需要进行适当的异常处理和其他调整。
文章来源:https://www.toymoban.com/diary/java/363.html
文章来源地址https://www.toymoban.com/diary/java/363.html
到此这篇关于Java应用程序中如何实现FTP功能 | 代码示例和教程的文章就介绍到这了,更多相关内容可以在右上角搜索或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!