sun.net.ftp.FtpClient 删除文件夹删除文件

sun.net.ftp.FtpClient 删除文件夹删除文件

这两天研究了一下 FtpClient  删除文件夹的功能,屡试不爽,发现一次性删除文件加和文件夹中的文件,删除不完全,总是要遗留一两个 没有删除的 所以没办法 采取以下方法 ,while循环

下面是实现的代码:欢迎提供好的解决方案,当前方案我不是很满意

 

package com.teenysoft.usermanager.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import sun.net.ftp.FtpClient;

public class FtpDele {

//测试

 public static void main(String[] args) {
  FtpDele fd = new FtpDele();
  fd.deleteZt("admin4","192.168.0.142","wgr","123");
 }


 public void deleteZt(String ztName,String ip,String username,String pass){

//循环,返回 true 表示没有删除完全,继续删除
  while(delete( ztName, ip, username, pass)){
   delete( ztName, ip, username, pass);
  }
 }

//删除的详细代码
 private boolean delete(String ztName,String ip,String username,String pass){
  boolean b = true;
  try{
   FtpClient ftpClient = new FtpClient();
   ftpClient.openServer(ip,21);//打开连接
   ftpClient.login(username,pass); //登陆FTP
   ftpClient.binary();
   ftpClient.serverIsOpen();

//注意红色部分是,删除完文件以后,又重新获取的ftpClient,,不然的话程序会跑死,具体原因我也不清楚,望高手指点
   List<String> l = new ArrayList<String>();
   deleteD(ftpClient,ztName,ztName,l);//获取要删除的所有文件夹中的文件路径
   for (String s : l) {
    ftpClient.sendServer("dele "+s+" \r\n");
   }
   ftpClient.closeServer();
   ftpClient.openServer(ip,21);
   ftpClient.login(username,pass); 
   ftpClient.binary(); 
   ftpClient.serverIsOpen();
   List<String> ll = new LinkedList<String>();
   deleteDD(ftpClient,ztName,ztName,ll);//获取所有要删除的文件夹的路径
   for (int i=(ll.size()-1);i>-1;i--) {
    ftpClient.sendServer("xrmd "+ll.get(i)+" \r\n");
   }
   ftpClient.sendServer("xrmd "+ztName+" \r\n");

 

//看看能不能找到根目录,如果可以则表示没有删除完,继续删除,报异常表示删除完成,返回false不继续删
   try{
    ftpClient.cd(ztName);
   }catch(Exception e){
    return false;
   }
   ftpClient.closeServer();
  }catch (Exception e) {
   return true;
  }
  return b;
 }
 private void deleteD(FtpClient ftpClient,String directory,String path,List<String> ll){
  try{
   List<String> files =  new ArrayList<String>();
   ftpClient.cd(directory);
   DataInputStream di=new DataInputStream(ftpClient.list());
   InputStreamReader in = new InputStreamReader(di);
   BufferedReader dis = new BufferedReader(in);
   String filename = "";
   while ((filename = dis.readLine()) != null) {
    filename = filename.trim();
    String s = filename.substring((filename.lastIndexOf(" ")+1),filename.length());
    if(!(s.equals(".") || s.equals(".."))){
     files.add(s);
    }
   }
   for(int i=0;i<files.size();i++){
    String fi = files.get(i);
    //暂时使用“.”的方式来判断是不是目录
    if(!(fi.indexOf(".")==-1)){
     ll.add(path + File.separator + fi);
    }else{
     String p2 = path + File.separator + fi;
     deleteD(ftpClient,fi,p2,ll);
    }
      }
   ftpClient.cd("..");
  }catch (Exception e) {
   e.getStackTrace();
  }
 }
 private void deleteDD(FtpClient ftpClient,String directory,String path,List<String> ll) throws Exception{
  try{
   List<String> files =  new ArrayList<String>();
   ftpClient.cd(directory);
   DataInputStream di=new DataInputStream(ftpClient.list());
   InputStreamReader in = new InputStreamReader(di);
   BufferedReader dis = new BufferedReader(in);
   String filename = "";
   while ((filename = dis.readLine()) != null) {
    filename = filename.trim();
    String s = filename.substring((filename.lastIndexOf(" ")+1),filename.length());
    if(!(s.equals(".") || s.equals(".."))){
     files.add(s);
    }
   }
   for(int i=0;i<files.size();i++){
    String fi = files.get(i);
    //暂时使用“.”的方式来判断是不是目录
    if(fi.indexOf(".")==-1){
     ll.add(path + File.separator + fi);
     String p2 = path + File.separator + fi;
     deleteDD(ftpClient,fi,p2,ll);
    }
      }
   ftpClient.cd("..");
  }catch (Exception e) {
   e.getStackTrace();
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
public class FTPUtil { private FTPClient ftpClient=null; private boolean result = false; private FileInputStream fis; String ftpHost = "10.16.111.111"; String port = 21 String ftpUserName = "ftpuser11; String ftpPassword = "1234561"; /** * 登录服务器 * @param ftpInfo * @return * @throws IOException */ public FTPClient login() throws IOException { ftpClient = new FTPClient(); ftpClient.connect(ftpHost); boolean login = ftpClient.login(ftpUserName,ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } if(login){ System.out.println("ftp连接成功!"); }else{ System.out.println("ftp连接失败!"); } //ftpClient.setControlEncoding("GBK"); return ftpClient; } /** * 字符串作为文件上传指定目录 下 * @param content 源字符串 * @param uploadDir 上传目录 * @param ftpFileName 上传文件名称 * @throws Exception */ public void ftpUploadByText(String content ,String uploadDir,String ftpFileName) throws Exception{ try { ftpClient = this.login(); //创建目录 createDir(ftpClient,uploadDir); // 设置上传目录 这个也应该用配置文件读取 ftpClient.changeWorkingDirectory(uploadDir); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); String fileName = new String(ftpFileName.getBytes("GBK"),"iso-8859-1"); OutputStream os = ftpClient.storeFileStream(fileName); byte[] bytes = content.getBytes(); os.write(bytes); os.flush(); os.close(); } catch (Exception e) { ftpClient.disconnect(); ftpClient = null; e.printStackTrace(); throw e; }finally{ ftpClient.disconnect(); ftpClient = null; } } /** * 移动文件 * @param ftpInfo * @return * @throws Exception */ public boolean moveFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.moveFile(ftpClient, ftpInfo.getChangeWorkingDirectoryPath(), ftpInfo.getFilePath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 删除文件 * @param ftpInfo * @return * @throws Exception */ public boolean deleteFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.deleteByFolder(ftpClient, ftpInfo.getChangeWorkingDirectoryPath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 实现文件的移动,这里做的是一个文件夹下的所有内容移动到新的文件, * 如果要做指定文件移动,加个判断判断文件名 * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName) * @param ftp * @param oldPath * @param newPath * @return */ public boolean moveFile(FTPClient ftp,String oldPath,String newPath){ boolean flag = false; try { ftp.changeWorkingDirectory(oldPath); ftp.enterLocalPassiveMode(); //获取文件数组 FTPFile[] files = ftp.listFiles(); //新文件夹不存在则创建 if(!ftp.changeWorkingDirectory(newPath)){ ftp.makeDirectory(newPath); } //回到原有工作目录 ftp.changeWorkingDirectory(oldPath); for (FTPFile file : files) { if(file.isDirectory()) { moveFile(ftp,oldPath+file.getName()+"/" ,newPath+file.getName()+"/"); }else{ //转存目录 flag = ftp.rename(oldPath+new String(file.getName().getBytes("GBK"),"ISO-8859-1"), newPath+"/"+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } if(flag){ System.out.println(file.getName()+"移动成功"); }else{ System.out.println(file.getName()+"移动失败"); } } ftp.removeDirectory(new String(oldPath.getBytes("GBK"),"ISO-8859-1")); } catch (Exception e) { e.printStackTrace(); System.out.println("移动文件失败"); } return flag; } /** * 删除FTP上指定文件夹文件及其子文件方法,添加了对中文目录的支持 * @param ftp FTPClient对象 * @param FtpFolder 需要删除文件夹 * @return */ public boolean deleteByFolder(FTPClient ftp,String FtpFolder){ boolean flag = false; try { ftp.changeWorkingDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); ftp.enterLocalPassiveMode(); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { //判断为文件删除 if(file.isFile()){ ftp.deleteFile(FtpFolder+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } //判断是文件夹 if(file.isDirectory()){ String childPath = FtpFolder +file.getName()+ "/"; //递归删除文件夹 deleteByFolder(ftp,childPath); } } //循环完成后删除文件夹 flag = ftp.removeDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); if(flag){ System.out.println(FtpFolder+"文件夹删除成功"); }else{ System.out.println(FtpFolder+"文件夹删除成功"); } } catch (Exception e) { e.printStackTrace(); System.out.println("删除失败"); } return flag; } /** * 创建目录 * @param createpath * @param sftp */ public void createDir(FTPClient ftpClient,String createpath) throws Exception { try { if(ftpClient.changeWorkingDirectory(createpath)) { return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if(!ftpClient.changeWorkingDirectory(filePath.toString())) { ftpClient.makeDirectory(filePath.toString()); ftpClient.changeWorkingDirectory(filePath.toString()); } } ftpClient.changeWorkingDirectory(createpath); }catch (Exception e) { e.printStackTrace(); throw new Exception("创建路径错误:" + createpath); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值