


Use java to implement simple FTP remote file management function (ftp software development 4)
本文为大家分享了FTP远程文件管理模块的实现方法,供大家参考,具体内容如下
首先看一下界面:
1、远程FTP服务器端的文件列表的显示
将远程的当前目录下所有文件显示出来,并显示文件的属性包括文件名、大小、日期、通过javax.swing.JTable()来显示具体的数据。更改当前文件目录会调用com.oyp.ftp.panel.ftp.FtpPanel类的listFtpFiles(final TelnetInputStream list)方法,其主要代码如下
/** * 读取FTP文件到表格的方法 * @param list * 读取FTP服务器资源列表的输入流 */ public synchronized void listFtpFiles(final TelnetInputStream list) { // 获取表格的数据模型 final DefaultTableModel model = (DefaultTableModel) ftpDiskTable .getModel(); model.setRowCount(0); // 创建一个线程类 Runnable runnable = new Runnable() { public synchronized void run() { ftpDiskTable.clearSelection(); try { String pwd = getPwd(); // 获取FTP服务器的当前文件夹 model.addRow(new Object[] { new FtpFile(".", pwd, true), "", "" }); // 添加“.”符号 model.addRow(new Object[] { new FtpFile("..", pwd, true), "", "" }); // 添加“..”符号 byte[]names=new byte[2048]; int bufsize=0; bufsize=list.read(names, 0, names.length); int i=0,j=0; while(i<bufsize){ //字符模式为10,二进制模式为13 // if (names[i]==10) { if (names[i]==13) { //获取字符串 -rwx------ 1 user group 57344 Apr 18 05:32 腾讯电商2013实习生招聘TST推荐模板.xls //文件名在数据中开始做坐标为j,i-j为文件名的长度,文件名在数据中的结束下标为i-1 String fileMessage = new String(names,j,i-j); if(fileMessage.length() == 0){ System.out.println("fileMessage.length() == 0"); break; } //按照空格将fileMessage截为数组后获取相关信息 // 正则表达式 \s表示空格,{1,}表示1一个以上 if(!fileMessage.split("\\s+")[8].equals(".") && !fileMessage.split("\\s+")[8].equals("..")){ /**文件大小*/ String sizeOrDir=""; if (fileMessage.startsWith("d")) {//如果是目录 sizeOrDir="<DIR>"; }else if (fileMessage.startsWith("-")) {//如果是文件 sizeOrDir=fileMessage.split("\\s+")[4]; } /**文件名*/ String fileName=fileMessage.split("\\s+")[8]; /**文件日期*/ String dateStr =fileMessage.split("\\s+")[5] +" "+fileMessage.split("\\s+")[6]+" " +fileMessage.split("\\s+")[7]; FtpFile ftpFile = new FtpFile(); // 将FTP目录信息初始化到FTP文件对象中 ftpFile.setLastDate(dateStr); ftpFile.setSize(sizeOrDir); ftpFile.setName(fileName); ftpFile.setPath(pwd); // 将文件信息添加到表格中 model.addRow(new Object[] { ftpFile, ftpFile.getSize(), dateStr }); } // j=i+1;//上一次位置为字符模式 j=i+2;//上一次位置为二进制模式 } i=i+1; } list.close(); } catch (IOException ex) { Logger.getLogger(FTPClientFrame.class.getName()).log( Level.SEVERE, null, ex); } } }; if (SwingUtilities.isEventDispatchThread()) // 启动线程对象 runnable.run(); else SwingUtilities.invokeLater(runnable); }
2、刷新远程FTP服务器端的文件列表
点击“刷新”按钮,会触发com.oyp.ftp.panel.ftp.RefreshAction类的actionPerformed(ActionEvent e)方法,其主要代码如下
/** 刷新按钮的动作处理器动作的事件处理方法 **/ @Override public void actionPerformed(ActionEvent e) { ftpPanel.refreshCurrentFolder(); // 调用刷新FTP资源列表的方法 }
上面的响应事件会调用com.oyp.ftp.panel.ftp.FtpPanel类的refreshCurrentFolder()方法,其主要代码如下
/** 刷新FTP资源管理面板的当前文件夹**/ public void refreshCurrentFolder() { try { // 获取服务器文件列表 TelnetInputStream list = ftpClient.list(); listFtpFiles(list); // 调用解析方法 } catch (IOException e) { e.printStackTrace(); } }
3、新建远程FTP服务器端的文件夹
点击“新建文件夹”按钮,会触发com.oyp.ftp.panel.ftp.CreateFolderAction类的actionPerformed(ActionEvent e)方法,然后弹出一个对话框,填写要新建的文件夹名称,选择“确定”,“取消”按钮结束。其主要代码如下
/** * 创建文件夹的事件处理方法 */ @Override public void actionPerformed(ActionEvent e) { // 接收用户输入的新建文件夹的名称 String folderName = JOptionPane.showInputDialog("请输入文件夹名称:"); if (folderName == null) return; int read = -1; try { // 发送创建文件夹的命令 ftpPanel.ftpClient.sendServer("MKD " + folderName + "\r\n"); // 读取FTP服务器的命令返回码 read = ftpPanel.ftpClient.readServerResponse(); } catch (IOException e1) { e1.printStackTrace(); } if (read == 257) {// 如果返回码等于257(路径名建立完成) // 提示文件夹创建成功 JOptionPane.showMessageDialog(ftpPanel, folderName + "文件夹,创建成功。", "创建文件夹", JOptionPane.INFORMATION_MESSAGE); }else{ // 否则 提示用户该文件夹无法创建 JOptionPane.showMessageDialog(ftpPanel, folderName + "文件夹无法被创建。", "创建文件夹", JOptionPane.ERROR_MESSAGE); } this.ftpPanel.refreshCurrentFolder(); }
4、 删除远程FTP服务器端的文件
选择好要删除的文件或文件夹,点击“删除”按钮,会触发com.oyp.ftp.panel.ftp.DelFileAction类的actionPerformed(ActionEvent e)方法,然后弹出一个对话框,选择“是”,“否”,“取消”按钮结束。其主要代码如下
public void actionPerformed(ActionEvent e) { // 获取显示FTP资源列表的表格组件当前选择的所有行 final int[] selRows = ftpPanel.ftpDiskTable.getSelectedRows(); if (selRows.length < 1) return; int confirmDialog = JOptionPane.showConfirmDialog(ftpPanel, "确定要删除吗?"); if (confirmDialog == JOptionPane.YES_OPTION) { Runnable runnable = new Runnable() { /** * 删除服务器文件的方法 * @param file - 文件名称 */ private void delFile(FtpFile file) { FtpClient ftpClient = ftpPanel.ftpClient; // 获取ftpClient实例 try { if (file.isFile()) { // 如果删除的是文件 ftpClient.sendServer("DELE " + file.getName() + "\r\n"); // 发送删除文件的命令 ftpClient.readServerResponse(); // 接收返回编码 } else if (file.isDirectory()) { // 如果删除的是文件夹 ftpClient.cd(file.getName()); // 进入到该文件夹 TelnetInputStream telnetInputStream=ftpClient.list(); byte[]names=new byte[2048]; int bufsize=0; bufsize=telnetInputStream.read(names, 0, names.length); int i=0,j=0; while(i<bufsize){ //字符模式为10,二进制模式为13 // if (names[i]==10) { if (names[i]==13) { //获取字符串 -rwx------ 1 user group 57344 Apr 18 05:32 腾讯电商2013实习生招聘TST推荐模板.xls //文件名在数据中开始做坐标为j,i-j为文件名的长度,文件名在数据中的结束下标为i-1 String fileMessage = new String(names,j,i-j); if(fileMessage.length() == 0){ System.out.println("fileMessage.length() == 0"); break; } //按照空格将fileMessage截为数组后获取相关信息 // 正则表达式 \s表示空格,{1,}表示1一个以上 if(!fileMessage.split("\\s+")[8].equals(".") && !fileMessage.split("\\s+")[8].equals("..")){ /**文件大小*/ String sizeOrDir=""; if (fileMessage.startsWith("d")) {//如果是目录 sizeOrDir="<DIR>"; }else if (fileMessage.startsWith("-")) {//如果是文件 sizeOrDir=fileMessage.split("\\s+")[4]; } /**文件名*/ String fileName=fileMessage.split("\\s+")[8]; /**文件日期*/ String dateStr =fileMessage.split("\\s+")[5] +fileMessage.split("\\s+")[6] +fileMessage.split("\\s+")[7]; FtpFile ftpFile = new FtpFile(); // 将FTP目录信息初始化到FTP文件对象中 ftpFile.setLastDate(dateStr); ftpFile.setSize(sizeOrDir); ftpFile.setName(fileName); ftpFile.setPath(file.getAbsolutePath()); // 递归删除文件或文件夹 delFile(ftpFile); } // j=i+1;//上一次位置为字符模式 j=i+2;//上一次位置为二进制模式 } i=i+1; } ftpClient.cdUp(); // 返回上层文件夹 ftpClient.sendServer("RMD " + file.getName() + "\r\n"); // 发送删除文件夹指令 ftpClient.readServerResponse(); // 接收返回码 } } catch (Exception ex) { Logger.getLogger(LocalPanel.class.getName()).log( Level.SEVERE, null, ex); } } /** * 线程的主体方法 */ public void run() { // 遍历显示FTP资源的表格的所有选择行 for (int i = 0; i < selRows.length; i++) { // 获取每行的第一个单元值,并转换为FtpFile类型 final FtpFile file = (FtpFile) ftpPanel.ftpDiskTable .getValueAt(selRows[i], 0); if (file != null) { delFile(file); // 调用删除文件的递归方法 try { // 向服务器发删除文件夹的方法 ftpPanel.ftpClient.sendServer("RMD " + file.getName() + "\r\n"); // 读取FTP服务器的返回码 ftpPanel.ftpClient.readServerResponse(); } catch (IOException e) { e.printStackTrace(); } } } // 刷新FTP服务器资源列表 DelFileAction.this.ftpPanel.refreshCurrentFolder(); JOptionPane.showMessageDialog(ftpPanel, "删除成功。"); } }; new Thread(runnable).start(); } }
5、重命名远程FTP服务器端的文件
选择好要重命名的文件或文件夹,点击“重命名”按钮,会触发com.oyp.ftp.panel.ftp.RenameAction类的actionPerformed(ActionEvent e)方法,其主要代码如下
/** * 重命名FTP文件的事件处理方法 */ @Override public void actionPerformed(ActionEvent e) { // 获取显示FTP资源的表格当前选择行号 int selRow = ftpPanel.ftpDiskTable.getSelectedRow(); if (selRow < 0) return; // 获取当前行的第一个表格单元值,并转换成FtpFile类型的对象 FtpFile file = (FtpFile) ftpPanel.ftpDiskTable.getValueAt(selRow, 0); // 使用对话框接收用户输入的新文件或文件夹名称 String newName = JOptionPane.showInputDialog(ftpPanel, "请输入新名称。"); if (file.getName().equals(".") || file.getName().equals("..") || newName == null) return; try { // 向服务器发送重命名的指令 ftpPanel.ftpClient.sendServer("RNFR " + file.getName() + "\r\n"); //对旧路径重命名 ftpPanel.ftpClient.readServerResponse(); ftpPanel.ftpClient.sendServer("RNTO " + newName + "\r\n"); //对新路径重命名 ftpPanel.ftpClient.readServerResponse(); ftpPanel.refreshCurrentFolder(); // 刷新当前文件夹 } catch (IOException e1) { e1.printStackTrace(); } }
The above is the detailed content of Use java to implement simple FTP remote file management function (ftp software development 4). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
