连接ftp服务器 JDK 1.7

连接ftp服务器 JDK 1.7

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import org.apache.log4j.Logger;

import com.zhiwei.core.util.AppUtil;

import java.net.InetSocketAddress;

import java.net.SocketAddress; 

import sun.net.TelnetInputStream;

import sun.net.TelnetOutputStream;

import sun.net.ftp.FtpClient;

import sun.net.ftp.FtpProtocolException;

public class  FtpUtils {

         protected static Logger LOG=Logger.getLogger(FtpUtils.class);

         private  FtpClient ftpClient=null;

        

         /**

     * 连接ftp服务器 JDK 1.7

     * 

     * @param url

     * @param port

     * @param username

     * @param password

     * @return FtpClient

     * @throws FtpProtocolException

     * @throws IOException

     */ 

    public  FtpClient connect(String url, int port, String username, 

            String password) { // 创建ftp 

        try { 

            // 创建地址 

            SocketAddress addr = new InetSocketAddress(url, port); 

            // 连接 

            ftpClient = FtpClient.create();

            ftpClient.setConnectTimeout(6000000);

            ftpClient.connect(addr); 

            // 登陆 

            ftpClient.login(username, password.toCharArray()); 

            ftpClient.setBinaryType();

           

            System.out.println(“——————————ftp服务器已连接———————-“); 

        } catch (FtpProtocolException e) { 

                 LOG.error(“ftp连接服务器出错,出错原因\r\n”, e);

        } catch (IOException e) { 

                 LOG.error(“ftp连接服务器出错,出错原因”, e);

        } 

        return ftpClient; 

    } 

        

    /**

     * 切换目录

     * 

     * @param ftp

     * @param path

     */ 

    public  void cd(String path) { 

        try { 

                 ftpClient.changeDirectory(path);

                 LOG.info(“切换目录”+ftpClient.getWorkingDirectory());

           // System.out.println(ftpClient.getWorkingDirectory()); 

        } catch (FtpProtocolException e) { 

                 LOG.error(“切换目录出错”,e);

        } catch (IOException e) { 

                 LOG.error(“切换目录出错”,e);

        } 

    } 

        

    //上传创建的文件夹或文件

    public void uploadDirectory(String directory,boolean bl,String nameFtp,String n,String serverIp,String username,String password)throws IOException, FtpProtocolException{

             if (ftpClient==null) {

                       Integer ss = Integer.valueOf(n);

                 connect(serverIp, ss,username , password);

             }

             File file=new File(directory);

                    String name=null;//待上传文件名

                    boolean result;

                    if(file.isDirectory()){ 

                             String dir = file.getName();

                                      if(bl){

                                                dir = nameFtp;

                                                bl = false;

                                      }

                                      result=isDirExist(ftpClient,dir);

                                      if (!result) {

                                                LOG.error(dir+”———-该文件夹已存在”); 

                                     }          

                             try {

                                     ftpClient.changeDirectory(dir);

                                     ftpClient.setBinaryType();

                            } catch (FtpProtocolException e) {

                                     LOG.error(“——进入”+dir+”文件夹失败——–“,e);

                            }   

                              String[] files = file.list();          

                               for (int i = 0; i < files.length; i++) {   

                                     File tmpFile = new File(file.getPath()+”\\”+files[i] );

                                      if(tmpFile.isDirectory()){

                                                 uploadDirectory(tmpFile.getAbsolutePath(),bl,nameFtp, n, serverIp, username, password);

                                       }else{

                                              name=tmpFile.getName();

                                         upload(directory+”/”+name, n, serverIp, username, password);     

                                        }              

                                }

                               ftpClient.changeToParentDirectory();

                             }else{   //文件上传

                                      upload(directory,file.getName(), n, serverIp, username, password);

                             }

          }

         //文件上传

    public void upload(String srcFile,String n,String serverIp,String username,String password)throws IOException{

                  

         File file=new File(srcFile);

         FileInputStream fin=new FileInputStream(srcFile);

         

        TelnetOutputStream tos = null;

         try {

                   tos = (TelnetOutputStream) ftpClient.putFileStream(file.getName(), true);

                   if(file.getName().equals(“spring.xml”)){

                            InputStreamReader ie=new InputStreamReader(fin, “utf-8”);

                            BufferedReader reader = new BufferedReader(ie);

                            String line = null;

                            while ((line = reader.readLine()) != null) {

                                     if(line.indexOf(“serverIp”)!=-1){

                                               line=line.replaceAll(“serverIp”, serverIp);

                                               line=line.replaceAll(“dataName”, n);

                                     }

                                     if(line.indexOf(“datausername”)!=-1){

                                               line=line.replaceAll(“datausername”, username);

                                     }

                                     if(line.indexOf(“datapassword”)!=-1){

                                               line=line.replaceAll(“datapassword”, password);

                                     }

                                     tos.write(line.getBytes(“utf-8”));

                            }

                            reader.close();

                            ie.close();

                   }else{

                            int readLength = 0;

                            byte[] buf = new byte[1024];

                            while ( (readLength = fin.read(buf)) != -1) {

                                     tos.write(buf, 0, readLength);

                            }

                   }

                   fin.close();

                   tos.close();

         } catch (Exception e) {

                   //System.out.println(“——–获取远程文件输出流失败—“);

                   LOG.error(“——–获取远程文件输出流失败—“,e );

         }

    }

    public void upload(String srcFile,String destFile,String n,String serverIp,String username,String password)throws IOException{

         upload(srcFile, n, serverIp, username, password);

         File file=new File(srcFile);

         //文件重命名 打开 上传 zip文件会报错 先关闭

        // ftpClient.rename(file.getName(), destFile);

        }

    public void close(){

         try {

          ftpClient.close();

         } catch (IOException e) {

          LOG.error(“关闭输出流失败”,e);

         }

        }

    /**

     * @param directory  上传文件在服务器上的存放路径

     * @param srcFilePath  要上传文件的存放路径

          * svn:songwj

          * 创建文件夹、调用上传方法进行上传

     * @throws FtpProtocolException

          */

          public void swjUploadDirectory(String directory,String srcFilePath,boolean bl,String nameFtp,String n,String serverIp,String username,String password,String dirStr)throws IOException, FtpProtocolException{

        

                    System.out.println(“服务器上要创建文件夹路径————-“+dirStr);

                    boolean result;

                    //1 创建各个节点的文件夹

                     if(!””.equals(dirStr)){

                              String dir =dirStr;

                              String url[] = dir.split(“/”);

                              for(int i = 0;i<url.length;i++){

                                       try {

                                               result=isDirExist(ftpClient,url[i]);

                                               if (result) {

                                                        LOG.info(“创建”+url[i]+”成功”);

                                               }else {

                                                        LOG.info(url[i]+”已存在”);

                                               }

                                               ftpClient.changeDirectory(url[i]);

                                               ftpClient.setBinaryType();

                                     } catch (FtpProtocolException e) {

                                               LOG.error(“——创建文件夹失败—–“, e);

                                     }

                              }

                     }

                     //2 调用上传方法上传文件

                     swjUpload(srcFilePath,directory, n, serverIp, username, password);

          }

          

          /** 判断Ftp目录是否存在

          * @throws FtpProtocolException */

          public boolean isDirExist(FtpClient ftpClient, String dir) {

          try{

                    ftpClient.makeDirectory(dir);

          } catch (FtpProtocolException  e1){

                    return false;

          }catch (IOException e) {

                    return false;

         }

          return true;

          }

          

          /**

           * 文件上传代码

           * @param srcFile  要上传文件的路径

           * @param fileToServerPath  上传文件存放在服务器上的位置

           * @param n

           * @param serverIp

           * @param username

           * @param password

           * @throws IOException

           */

          public void swjUpload(String srcFile,String fileToServerPath,String n,String serverIp,String username,String password)throws IOException{

                  

           //创建一个文件(服务器上对应的文件)

      File serverFile = new File(fileToServerPath);

     

      //创建选择要上传的文件对象

           File srFile=new File(srcFile);

          

           //把上传的文件对象放入文件流中

           FileInputStream fin=new FileInputStream(srcFile);

           LOG.info(“上传到服务器地址===”+fileToServerPath);

           //System.out.println(“fileToServerPath===”+fileToServerPath);

           //打开ftp上的文件 准备接收

           TelnetOutputStream tos = null;

         try {

                   tos = (TelnetOutputStream) ftpClient.putFileStream(serverFile.getName(), true);

                   if(srFile.getName().equals(“spring.xml”)){

                        InputStreamReader ie=new InputStreamReader(fin, “utf-8”);

                        BufferedReader reader = new BufferedReader(ie);//读取要上传的 文件

                        String line = null;

                        while ((line = reader.readLine()) != null) {

                                 if(line.indexOf(“serverIp”)!=-1){

                                           line=line.replaceAll(“serverIp”, serverIp);

                                           line=line.replaceAll(“dataName”, n);

                                 }

                                 if(line.indexOf(“datausername”)!=-1){

                                           line=line.replaceAll(“datausername”, username);

                                 }

                                 if(line.indexOf(“datapassword”)!=-1){

                                           line=line.replaceAll(“datapassword”, password);

                                 }

                                 tos.write(line.getBytes(“utf-8”));

                      }

                      reader.close();

                      ie.close();

                     }else{

                      int readLength = 0;

                      byte[] buf = new byte[1024];

                      while ( (readLength = fin.read(buf)) != -1) {

                          tos.write(buf, 0, readLength);//把要上传文件流写入服务器的文件中

                      }

                     }

                    tos.close();

         } catch (Exception e) {

                   LOG.error(“上传文件到服务器失败”, e);

         }

          fin.close();

          }

          

          /**

           * Ftp 服务器文件下载单个文件

           * svn:songwj

           * @param srcStr  要下载文件的路径

           * @param disStr  下载文件存放的路径

           */

          public  void  ftpDownFile(String srcStr,String disStr) {

                    

                   // 读取配置文件读取ftp ip地址 端口号  账户  密码

                            String ip = AppUtil.getFtpIp();

                            String us = AppUtil.getFtpUsName();//帐号

                            String ps = AppUtil.getFtpPss();//密码

                            int port = Integer.valueOf(AppUtil.getFtpPort());//端口 默认为 21

                            connect(ip, port, us, ps);

                   TelnetInputStream is = null;

        FileOutputStream os = null;

       

        System.out.println(“srcStr——————–“+srcStr);

        System.out.println(“disStr——————–“+disStr);

       

       

        try {

            //获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。

            ftpClient.changeDirectory(srcStr);

            is = (TelnetInputStream) ftpClient.getFileStream(srcStr);

         

            System.out.println(“os——————–“+os.toString());

 

            byte[] bytes = new byte[2048];

            int c;

            while ((c = is.read(bytes)) != -1) {

                os.write(bytes, 0, c);

            }

            System.out.println(“—————-下载成功—————-“);

        } catch (IOException ex) {

            //System.out.println(“下载失败”);

            LOG.error(“—————下载失败————–“, ex);

            throw new RuntimeException(ex);

        } catch (FtpProtocolException e) {

                 LOG.error(“—————-下载失败—————-“, e);

                   } finally{

            try {

                if(is != null){

                    is.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            } finally {

                try {

                    if(os != null){

                        os.close();

                    }

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

          }

          /**

           * 删除ftp服务器上指定的文件

           * @param fileName

           */

          public String  removeFile(String deleteFilePath){

                    

                    System.out.println(“———进入到删除方法中”);

                    String resultStr = “”;

                    

                    if(ftpClient!= null){

                              try {

                                      

                                       ftpClient.deleteFile(deleteFilePath);

                                     //ftpClient.deleteFile(“D:/sendMessagePicture.png”);

                                     //ftpClient.deleteFile( “D:\\sendMessagePicture.png”);

                                     resultStr = ftpClient.getLastResponseString();

                                     //FtpReplyCode lastReplyCode = ftpClient.getLastReplyCode();

                                     System.out.println(“status—————-“+resultStr);

                            } catch (Exception e) {

                                     LOG.error(“删除失败”, e);

                            }

                    }else{

                             resultStr = “FAIL”;

                    }

                   return resultStr;

          }

         }

转载于:https://www.cnblogs.com/chinaifae/p/10401481.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/101113.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 操作系统实验一进程管理实验报告(进程的管理和控制实验报告)

    实验一进程管理1.目的和要求通过实验理解进程的概念,进程的组成(PCB结构),进程的并发执行和操作系统进行进程管理的相关原语(主要是进程的创建、执行、撤消)。2.实验内容用C语言编程模拟进程管理,至少要有:创建新的进程;查看运行进程;换出某个进程;杀死运行进程以及进程之间通信等功能。3.实验环境Windows操作系统、VC++6.0C语言4.实验提示PCB结…

  • python中绝对值的表达式

    python中绝对值的表达式abs(x)print(abs(23))#23print(abs(-45))#45

  • centos 普通用户 和 root 相互切换方法

    centos 普通用户 和 root 相互切换方法

  • NTU NUS 申请经历

    NTU NUS 申请经历我的出国历程                ——考研+出国全纪录个人简历:本人,男,1989年出生,东北大学秦皇岛分校06级通信工程专业学生。在校期间曾获得校一等奖学金1次,二等奖学金2次,三等奖学金2次,科技创新奖学金1次,鹏远奖学金1次。曾获得校“东软杯”科技竞赛特等奖,“挑战杯”课外学术作品竞赛省三等奖,并参加过全国大学生数学建模比赛。在校期间多次获得康师傅“再来一瓶”奖励。

  • UML类图介绍

    UML类图介绍文章目录UML类图一、类图概述二、类图的作用三、类图表示法1.类的表示方式2.类与类之间关系的表示方式2.1关联关系2.2聚合关系2.3组合关系2.4依赖关系2.5继承关系2.6实现关系UML类图一、类图概述类图显示了模型中存在的类、类的内部结构以及它们与其他类的关系二、类图的作用类图描述了系统的类的集合,类的属性和类之间的关系,可以简化了人们对系统的理解三、类图表示法1.类的表示方式在UML类图中,类使用包含类名、属性和方法且带有分割线的矩形来表示比如下图表示一个Emp

  • ❄️全网最详细的Python入门基础教程,Python最全教程(非常详细,整理而来)

    ❄️全网最详细的Python入门基础教程,Python最全教程(非常详细,整理而来)最近想要学习Python,所以就在网上整理了好多整理而来超级详细的Python入门教程

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号