sun.net.ftp.FtpClient上传,下载,移动文件,修改文件等等

本文介绍了一个用于FTP客户端操作的实用类,包括连接服务器、上传和下载文件、获取文件列表等功能,并提供了详细的实现代码。
public class ftpclientutil {
ftpclient ftpclient;
private string server;
private int port;
private string username;
private string userpassword;

public ftpclientutil(string server,int port,string username,string userpassword)
{
 this.server=server;
 this.port=port;
 this.username=username;
 this.userpassword=userpassword;
}
/**
 * 链接到服务器
 * @return
 */
public boolean open()
{
 if(ftpclient!=null&&ftpclient.serverisopen())
  return true;
 try
 {
     ftpclient= new ftpclient();
     ftpclient.openserver(server,port);
     ftpclient.login(username, userpassword);
     ftpclient.binary();
     return true;
 }
 catch(exception e)
 {
  e.printstacktrace();
  ftpclient=null;
  return false;
 }
}

public boolean cd(string dir){
 boolean f = false;
 try {
   ftpclient.cd (dir);
 } catch (ioexception e) {
  logs.error(e.tostring());
  return f;
 }
 return true;
}

/**
 * 上传文件到ftp服务器
 * @param localpathandfilename 本地文件目录和文件名
 * @param ftpfilename  上传后的文件名
 * @param ftpdirectory ftp目录如:/path1/pathb2/,如果目录不存在回自动创建目录
 * @throws exception
 */
public boolean upload(string localdirectoryandfilename,string ftpfilename,string ftpdirectory)throws exception {
 if(!open())
  return false;
 fileinputstream is=null;
 telnetoutputstream os=null;
 try
 {
  char ch = ' ';
  if (ftpdirectory.length() > 0)
   ch = ftpdirectory.charat(ftpdirectory.length() - 1);
  for (; ch == '/' || ch == '\\'; ch = ftpdirectory.charat(ftpdirectory.length() - 1))
   ftpdirectory = ftpdirectory.substring(0, ftpdirectory.length() - 1);

  int slashindex = ftpdirectory.indexof(47);
  int backslashindex = ftpdirectory.indexof(92);
  int index = slashindex;
  string dirall = ftpdirectory;
  if (backslashindex != -1 && (index == -1 || index > backslashindex))
   index = backslashindex;
  string directory = "";
  while (index != -1) {
   if (index > 0) {
    string dir = dirall.substring(0, index);
    directory = directory + "/" + dir;
    ftpclient.sendserver("xmkd " + directory + "\r\n");
    ftpclient.readserverresponse();
   }
   dirall = dirall.substring(index + 1);
   slashindex = dirall.indexof(47);
   backslashindex = dirall.indexof(92);
   index = slashindex;
   if (backslashindex != -1 && (index == -1 || index > backslashindex))
    index = backslashindex;
  }
  ftpclient.sendserver("xmkd " + ftpdirectory + "\r\n");
  ftpclient.readserverresponse();

  os = ftpclient.put(ftpdirectory + "/"
    + ftpfilename);
  file file_in = new file(localdirectoryandfilename);
  is = new fileinputstream(file_in);
  byte bytes[] = new byte[1024];
  int i;
  while ((i = is.read(bytes)) != -1)
   os.write(bytes, 0, i);
  //清理垃圾
  
   
  return true;
 }
 catch(exception e)
 {
  e.printstacktrace();
  return false;
 }
 finally
 {
  if (is != null) 
     is.close();
  if (os != null) 
     os.close();
 }
}
/**
 * 从ftp服务器上下载文件并返回下载文件长度
 * @param ftpdirectoryandfilename
 * @param localdirectoryandfilename
 * @return
 * @throws exception
 */
public long download(string ftpdirectoryandfilename,string localdirectoryandfilename)throws exception 
{
 long result = 0; 
 if(!open())
  return result;
 telnetinputstream is = null; 
 fileoutputstream os = null;
 try  
 { 
       is = ftpclient.get(ftpdirectoryandfilename);        
       java.io.file outfile = new java.io.file(localdirectoryandfilename); 
       os = new fileoutputstream(outfile); 
       byte[] bytes = new byte[1024]; 
       int c; 
       while ((c = is.read(bytes)) != -1) 
       { 
           os.write(bytes, 0, c); 
           result = result + c; 
       } 
    }
 catch (exception e)  
 { 
        throw e;
 } 
 finally 
 { 
     if (is != null) 
       is.close();
     if (os != null) 
       os.close();
     
  }
     return result; 

/**
 * 返回ftp目录下的文件列表
 * @param ftpdirectory
 * @return
 */
 public list<string> getfilenamelist(string ftpdirectory) 
 { 
    list<string> list = new arraylist<string>(); 
    if(!open())
  return list;
    try  
    { 
       datainputstream dis = new  datainputstream(ftpclient.namelist(ftpdirectory)); 
       string filename = ""; 
       while((filename=dis.readline())!=null)   
       {
         list.add(filename);         
       }   
    } catch (exception e)  
    { 
       e.printstacktrace(); 
    } 
    return list; 
 }
 /**
  * 删除ftp上的文件
  * @param ftpdirandfilename
  */
 public boolean deletefile(string ftpdirandfilename)
 {
  if(!open())
  return false;
  ftpclient.sendserver("dele "+ftpdirandfilename+"\r\n");
  return true;
 }
 /**
  * 删除ftp目录
  * @param ftpdirectory
  */
 public boolean deletedirectory(string ftpdirectory)
 {
  if(!open())
  return false;
  ftpclient.sendserver("xrmd "+ftpdirectory+"\r\n");
  return true;
 }
 /**
  * 关闭链接
  */
 public void close()
 {
  try
  {
      if(ftpclient!=null&&ftpclient.serverisopen())
       ftpclient.closeserver();
  }catch(exception e)
  {
   
  }
 }

}


狗粮排行榜

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); } } }
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值