FTPClient

来源:互联网 发布:2017单反推荐 知乎 编辑:程序博客网 时间:2024/05/21 15:41
1. 
Java代码  收藏代码
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5.   
  6. import org.apache.commons.logging.Log;  
  7. import org.apache.commons.logging.LogFactory;  
  8.   
  9.   
  10. import sun.net.TelnetInputStream;  
  11. import sun.net.TelnetOutputStream;  
  12. import sun.net.ftp.FtpClient;  
  13.   
  14. public class FtpBusiness {  
  15.     private final static Log logger = LogFactory.getLog(FtpBusiness.class);  
  16.   
  17.     /** 
  18.      * 创建连接 
  19.      *  
  20.      * @param IP FTP服务器地址 
  21.      * @param userName FTP服务器用户名 
  22.      * @param passWord FTP服务器密码 
  23.      * @return 
  24.      * @throws Exception 
  25.      */  
  26.     public FtpClient ftpConnection(String IP, String userName, String passWord)  
  27.             throws Exception {  
  28.         FtpClient fc = null;  
  29.         try {  
  30.             fc = new FtpClient();  
  31.             fc.openServer(IP);  
  32.             fc.login(userName, passWord);  
  33.             fc.binary();  
  34.         } catch (Exception e) {  
  35.             logger.error(e);  
  36.         }  
  37.         return fc;  
  38.     }  
  39.   
  40.     /** 
  41.      * 关闭连接 
  42.      *  
  43.      * @param fc FTP连接对象 
  44.      * @return 
  45.      */  
  46.     public boolean ftpClose(FtpClient fc) {  
  47.         try {  
  48.             fc.closeServer();  
  49.         } catch (Exception e) {  
  50.             logger.error(e);  
  51.             return false;  
  52.         }  
  53.         return true;  
  54.     }  
  55.   
  56.     /** 
  57.      * 获取当前目录 
  58.      *  
  59.      * @param fc FTP连接对象 
  60.      * @return 
  61.      */  
  62.     public String ftpPWD(FtpClient fc){  
  63.         try {  
  64.             return fc.pwd();  
  65.         } catch (Exception e) {  
  66.             logger.error(e);  
  67.             return null;  
  68.         }  
  69.     }  
  70.   
  71.     public void ftpCD(FtpClient fc, String path){  
  72.         try {  
  73.             fc.cd(path);  
  74.         } catch (Exception e) {  
  75.             logger.error("FTP 转换到目录" + path + "异常:" + e);  
  76.         }  
  77.     }  
  78.   
  79.     /** 
  80.      * 获取文件列表 
  81.      *  
  82.      * @param fc FTP连接对象 
  83.      * @return 
  84.      * @throws Exception 
  85.      */  
  86.     public String ftpList(FtpClient fc){  
  87.         try {  
  88.             TelnetInputStream is = fc.list();  
  89.             StringBuffer sb = new StringBuffer();  
  90.             int k;  
  91.             while ((k = is.read()) != -1) {  
  92.                 sb.append((char) k);  
  93.             }  
  94.             is.close();  
  95.             return new String(sb.toString().getBytes("iso-8859-1"), "GBK");  
  96.         } catch (Exception e) {  
  97.             logger.error(e);  
  98.             return null;  
  99.         }  
  100.     }  
  101.   
  102.     /** 
  103.      * 下载文件 
  104.      *  
  105.      * @param fc FTP连接对象 
  106.      * @param filename 下载的文件名称 
  107.      * @return 
  108.      * @throws Exception 
  109.      */  
  110.     public InputStream getFile(FtpClient fc, String filename){  
  111.         InputStream is = null;  
  112.         try {  
  113.             fc.binary();  
  114.             is = fc.get(filename);  
  115.             return is;  
  116.         } catch (Exception e) {  
  117.             logger.error("下载文件:" + filename + " 异常");  
  118.             return null;  
  119.         }  
  120.     }  
  121.   
  122.     /** 
  123.      * 上传文件 
  124.      *  
  125.      * @param fc FTP连接对象 
  126.      * @param filename  上传的文件名称 
  127.      * @return 
  128.      * @throws IOException 
  129.      */  
  130.     public boolean ftpPut(FtpClient fc, String filename, String Url) {  
  131.         FileInputStream is = null;  
  132.         TelnetOutputStream os = null;  
  133.   
  134.         try {  
  135.   
  136.             os = fc.put(filename);  
  137.             File file_in = new File(Url);  
  138.             is = new FileInputStream(file_in);  
  139.             byte[] bytes = new byte[1024];  
  140.             int c;  
  141.             while ((c = is.read(bytes)) != -1) {  
  142.                 os.write(bytes, 0, c);  
  143.             }  
  144.         } catch (IOException ex) {  
  145.             logger.error(ex);  
  146.             return false;  
  147.         } finally {  
  148.             try {  
  149.                 is.close();  
  150.                 os.close();  
  151.             } catch (Exception e) {  
  152.                 logger.error(e);  
  153.             }  
  154.   
  155.         }  
  156.         return true;  
  157.     }  
  158.     /** 
  159.      * 删除文件 
  160.      *  
  161.      * @param fc FTP连接对象 
  162.      * @param filename 删除的文件名称 
  163.      * @return 
  164.      */  
  165.     public boolean ftpDelete(FtpClient fc, String filename) {  
  166.         try {  
  167.             fc.cd(ftpPWD(fc));  
  168.         } catch (IOException e) {  
  169.             logger.error(e);  
  170.             return false;  
  171.         }   
  172.         fc.sendServer("dele " + filename + "\r\n");  
  173.         try {  
  174.             fc.readServerResponse();  
  175.         } catch (IOException e) {  
  176.             logger.error(e);  
  177.         }  
  178.         return true;  
  179.     }  
  180.       
  181.     public static void main(String[] args) throws Exception {  
  182.         String IP = "111.222.333.444";  
  183.         String userName = "testftpU";  
  184.         String userPassword = "testftpP";  
  185.         FtpClient fc = null;  
  186.         String fileList = "";  
  187.         // 文件名为项目路径下的文件  
  188.         String upFileName = "d:\\a.txt";  
  189.         String dictionary = "";  
  190.         FtpBusiness ftp = new FtpBusiness();  
  191.   
  192.         // 链接FTP  
  193.         fc = ftp.ftpConnection(IP, userName, userPassword);  
  194.         // 获得文件列表  
  195.         fileList = ftp.ftpList(fc);  
  196.         logger.info("当前文件列表:\n" + fileList);  
  197.         // 获得当前目录  
  198.         dictionary = ftp.ftpPWD(fc);  
  199.         logger.info("当前目录:" + dictionary);  
  200.         // 上传文件  
  201.         ftp.ftpPut(fc, upFileName, "d:\\a.txt");  
  202.         // 下载文件  
  203.         // ftp.getFile(fc, "b.txt");  
  204.         // 删除文件  
  205.         // ftp.ftpDelete(fc, "PSS.rar");  
  206.   
  207.         // 关闭连接  
  208.         ftp.ftpClose(fc);  
  209.     }  
  210.   
  211. }  




Java代码  收藏代码
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8.   
  9. import org.apache.commons.net.ftp.FTP;  
  10. import org.apache.commons.net.ftp.FTPClient;  
  11. import org.apache.commons.net.ftp.FTPClientConfig;  
  12. import org.apache.commons.net.ftp.FTPFile;  
  13. import org.apache.commons.net.ftp.FTPReply;  
  14.   
  15. public class ftpTest {  
  16.     /** 
  17.      * 获得连接-FTP方式 
  18.      * @param hostname FTP服务器地址 
  19.      * @param port FTP服务器端口 
  20.      * @param username FTP登录用户名 
  21.      * @param password FTP登录密码 
  22.      * @return FTPClient 
  23.      */  
  24.     public FTPClient getConnectionFTP(String hostName, int port, String userName, String passWord) {  
  25.         //创建FTPClient对象  
  26.         FTPClient ftp = new FTPClient();  
  27.         try {  
  28.             //连接FTP服务器  
  29.             ftp.connect(hostName, port);  
  30.             //下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件  
  31.             ftp.setControlEncoding("GBK");  
  32.             FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);  
  33.             conf.setServerLanguageCode("zh");  
  34.             //登录ftp  
  35.             ftp.login(userName, passWord);  
  36.             if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {  
  37.                 ftp.disconnect();  
  38.                 System.out.println("连接服务器失败");  
  39.             }  
  40.             System.out.println("登陆服务器成功");  
  41.         } catch (IOException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.         return ftp;  
  45.     }  
  46.       
  47.     /** 
  48.      * 关闭连接-FTP方式 
  49.      * @param ftp FTPClient对象 
  50.      * @return boolean 
  51.      */  
  52.     public boolean closeFTP(FTPClient ftp) {  
  53.         if (ftp.isConnected()) {  
  54.             try {  
  55.                 ftp.disconnect();  
  56.                 System.out.println("ftp已经关闭");  
  57.                 return true;  
  58.             } catch (Exception e) {  
  59.                 e.printStackTrace();  
  60.             }  
  61.         }  
  62.         return false;  
  63.     }  
  64.       
  65.     /** 
  66.      * 上传文件-FTP方式 
  67.      * @param ftp FTPClient对象 
  68.      * @param path FTP服务器上传地址 
  69.      * @param filename 本地文件路径 
  70.      * @param inputStream 输入流 
  71.      * @return boolean 
  72.      */  
  73.     public boolean uploadFile(FTPClient ftp, String path, String fileName, InputStream inputStream) {  
  74.         boolean success = false;  
  75.         try {  
  76.             ftp.changeWorkingDirectory(path);//转移到指定FTP服务器目录  
  77.             FTPFile[] fs = ftp.listFiles();//得到目录的相应文件列表  
  78.             fileName = ftpTest.changeName(fileName, fs);  
  79.             fileName = new String(fileName.getBytes("GBK"),"ISO-8859-1");  
  80.             path = new String(path.getBytes("GBK"), "ISO-8859-1");  
  81.             //转到指定上传目录  
  82.             ftp.changeWorkingDirectory(path);  
  83.             //将上传文件存储到指定目录  
  84.             ftp.setFileType(FTP.BINARY_FILE_TYPE);  
  85.             //如果缺省该句 传输txt正常 但图片和其他格式的文件传输出现乱码  
  86.             ftp.storeFile(fileName, inputStream);  
  87.             //关闭输入流  
  88.             inputStream.close();  
  89.             //退出ftp  
  90.             ftp.logout();  
  91.             //表示上传成功  
  92.             success = true;  
  93.             System.out.println("上传成功。。。。。。");  
  94.         } catch (Exception e) {  
  95.             e.printStackTrace();  
  96.         }  
  97.         return success;  
  98.     }  
  99.   
  100.     /** 
  101.      * 删除文件-FTP方式 
  102.      * @param ftp FTPClient对象 
  103.      * @param path FTP服务器上传地址 
  104.      * @param filename FTP服务器上要删除的文件名 
  105.      * @return 
  106.      */  
  107.     public boolean deleteFile(FTPClient ftp, String path, String fileName) {  
  108.         boolean success = false;  
  109.         try {  
  110.             ftp.changeWorkingDirectory(path);//转移到指定FTP服务器目录  
  111.             fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");  
  112.             path = new String(path.getBytes("GBK"), "ISO-8859-1");  
  113.             ftp.deleteFile(fileName);  
  114.             ftp.logout();  
  115.             success = true;  
  116.         } catch (Exception e) {  
  117.             e.printStackTrace();  
  118.         }  
  119.         return success;  
  120.     }  
  121.   
  122.     /** 
  123.      * 上传文件-FTP方式 
  124.      * @param ftp FTPClient对象 
  125.      * @param path FTP服务器上传地址 
  126.      * @param fileName 本地文件路径 
  127.      * @param localPath 本里存储路径 
  128.      * @return boolean 
  129.      */  
  130.     public boolean downFile(FTPClient ftp, String path, String fileName, String localPath) {  
  131.         boolean success = false;  
  132.         try {  
  133.             ftp.changeWorkingDirectory(path);//转移到FTP服务器目录  
  134.             FTPFile[] fs = ftp.listFiles(); //得到目录的相应文件列表  
  135.             for (FTPFile ff : fs) {  
  136.                 if (ff.getName().equals(fileName)) {  
  137.                     File localFile = new File(localPath + "\\" + ff.getName());  
  138.                     OutputStream outputStream = new FileOutputStream(localFile);  
  139.                     //将文件保存到输出流outputStream中  
  140.                     ftp.retrieveFile(new String(ff.getName().getBytes("GBK"), "ISO-8859-1"), outputStream);  
  141.                     outputStream.flush();  
  142.                     outputStream.close();  
  143.                     System.out.println("下载成功");  
  144.                 }  
  145.             }  
  146.             ftp.logout();  
  147.             success = true;  
  148.         } catch (Exception e) {  
  149.             e.printStackTrace();  
  150.         }  
  151.         return success;  
  152.     }  
  153.       
  154.     /** 
  155.      * 判断是否有重名文件 
  156.      * @param fileName 
  157.      * @param fs 
  158.      * @return 
  159.      */  
  160.     public static boolean isFileExist(String fileName, FTPFile[] fs) {  
  161.         for (int i = 0; i < fs.length; i++) {  
  162.             FTPFile ff = fs[i];  
  163.             if (ff.getName().equals(fileName)) {  
  164.                 return true//如果存在返回 正确信号  
  165.             }  
  166.         }  
  167.         return false//如果不存在返回错误信号  
  168.     }  
  169.   
  170.     /** 
  171.      * 根据重名判断的结果 生成新的文件的名称 
  172.      * @param fileName 
  173.      * @param fs 
  174.      * @return 
  175.      */  
  176.     public static String changeName(String fileName, FTPFile[] fs) {  
  177.         int n = 0;  
  178. //      fileName = fileName.append(fileName);  
  179.         while (isFileExist(fileName.toString(), fs)) {  
  180.             n++;  
  181.             String a = "[" + n + "]";  
  182.             int b = fileName.lastIndexOf(".");//最后一出现小数点的位置  
  183.             int c = fileName.lastIndexOf("[");//最后一次"["出现的位置  
  184.             if (c < 0) {  
  185.                 c = b;  
  186.             }  
  187.             StringBuffer name = new StringBuffer(fileName.substring(0, c));//文件的名字  
  188.             StringBuffer suffix = new StringBuffer(fileName.substring(b + 1));//后缀的名称  
  189.             fileName = name.append(a) + "." + suffix;  
  190.         }  
  191.         return fileName.toString();  
  192.     }  
  193.   
  194.     /** 
  195.      *  
  196.      * @param args 
  197.      *  
  198.      * @throws FileNotFoundException 
  199.      *  
  200.      * 测试程序 
  201.      *  
  202.      */  
  203.     public static void main(String[] args) throws FileNotFoundException {  
  204.   
  205.         String path = "/home1/ftproot/textftp/test/";  
  206.         File f1 = new File("d:\\a.txt");  
  207.         String filename = f1.getName();  
  208.         System.out.println(filename);  
  209.         //InputStream input = new FileInputStream(f1);  
  210.         //ftpTest a = new ftpTest();  
  211.         //a.uploadFile("172.25.5.193", 21, "shiyanming", "123", path, filename, input);  
  212.         /* 
  213.          * String path ="D:\\ftpindex\\"; File f2 = new 
  214.          * File("D:\\ftpindex\\old.txt"); String filename2= f2.getName(); 
  215.          * System.out.println(filename2); ftpTest a = new 
  216.          * ftpTest(); a.downFile("172.25.5.193", 21, "shi", "123", path, 
  217.          * filename2, "C:\\"); 
  218.          */  
  219.         ftpTest a = new ftpTest();  
  220.         InputStream input = new FileInputStream(f1);  
  221. //      a.uploadFile("218.108.250.205", 21, "hwyhftp", "!#hwyhftp", path, filename, input);  
  222.         //a.deleteFile("218.108.250.205", 21, "hwyhftp", "!#hwyhftp", path, filename);  
  223. //      a.downFile("218.108.250.205", 21, "hwyhftp", "!#hwyhftp", path, "欢[2].txt");  
  224.         FTPClient ftp = a.getConnectionFTP("111.222.333.444"21"testU""testP");  
  225. //      a.deleteFile(ftp, path, "a[2].txt");  
  226.         a.uploadFile(ftp, path, filename, input);  
  227.         a.closeFTP(ftp);  
  228.     }  
  229. }  
0 0