设为首页 收藏本站
查看: 865|回复: 0

[经验分享] ftp文件上传下载

[复制链接]

尚未签到

发表于 2016-6-8 07:37:56 | 显示全部楼层 |阅读模式
  
  package isale.ftp.test;
  import java.io.IOException;
import java.io.OutputStream;
  import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
  /**
* 使用commons的net包进行ftp链接. 相关包:commons-net-1.4.1.jar ;
* commons-io-1.2.jar;jakarta-oro-2.0.8.jar测试通过.可以列出ftp上的文件
* 通过把ftp服务器上的文件流连接到outSteam及可以把文件下载到本机的目录..限制如果目录为中文则需要处理.最好使用英文文件名
*
* @author xzgf email:
*
*
* @create 2007-2-11
*
*/
public class ListFtpFile {
  private FTPClient ftpClient = new FTPClient();
  private OutputStream outStream = null;
  /**
   * ftp服务器地址
   */
private String hostName = "192.168.0.3";
  /**
   * 登录名
   */
private String userName = "isale";
  /**
   * 登录密码
   */
private String password = "isale";
  /**
   * 需要访问的远程目录
   */
private String remoteDir = "/bugzillaBackup";
  /**
   * 登录方法
   *
   */
private void login() {
   try {
    // 链接到ftp服务器
    ftpClient.connect(hostName);
    System.out.println("连接到ftp服务器:" + hostName + " 成功..开始登录");
    // 登录.用户名 密码
    ftpClient.login(userName, password);
    System.out.println("登录成功.");
  FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir);
    System.out.println("目录" + remoteDir + "下的文件:");
    if (remoteFiles != null) {
     for (int i = 0; i < remoteFiles.length; i++) {
      String name = remoteFiles.getName();
      long length = remoteFiles.getSize();
      String readableLength = FileUtils
        .byteCountToDisplaySize(length);
      System.out.println(name + ":\t\t" + readableLength);
     }
    }
  } catch (Exception e) {
    e.printStackTrace();
   } finally {
    // 使用IO包关闭流
    if (outStream == null) {
     System.out.println("outStream is null.");
    }
    IOUtils.closeQuietly(outStream);
    try {
     ftpClient.disconnect();
    } catch (IOException ioe) {
     ioe.printStackTrace();
    }
   }
}
  public static void main(String[] args) {
   ListFtpFile listFtpfiles = new ListFtpFile();
   listFtpfiles.login();
}
}
  package isale.ftp.test;
  import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
  public class FtpClientCommonNetImpl {
// ftp配置
private Properties config;
  protected FTPClient connectFtpServer() throws Exception {
   String server = this.config.getProperty("server");
   String userName = this.config.getProperty("userName");
   String password = this.config.getProperty("password");
   // 创建ftp客户端对象
   FTPClient ftp = new FTPClient();
   try {
   ftp.configure(this.getFTPClientConfig());
    // 连接ftp服务器
   ftp.connect(server);
    // 登录
   ftp.login(userName, password);
  // 返回值
    int reply = ftp.getReplyCode();
    if ((!FTPReply.isPositiveCompletion(reply))) {
    ftp.disconnect();
     throw new Exception("登录ftp服务器失败,请检查server[" + server
       + "]、username[" + userName + "]、password[" + password
       + "]是否正确!");
    } else {
     System.out.println("登陆成功");
    }
  return ftp;
   } catch (Exception ex) {
    throw ex;
   }
}
  /**
   * 关闭连接
   *
   * @param ftp
   * @throws Exception
   */
protected void disconnectFtpServer(FTPClient ftp) throws Exception {
   try {
   ftp.logout();
   ftp.disconnect();
   } catch (Exception ex) {
    throw ex;
   }
}
  /**
   * 上传
   *
   * @throws Exception
   */
public void upload(InputStream localIn, String remoteFilePath)
    throws Exception {
   /*
    * String server = this.config.getProperty("server"); String userName =
    * this.config.getProperty("userName"); String password =
    * this.config.getProperty("password");
    */
   FTPClient ftp = this.connectFtpServer();
  try {
    boolean result = ftp.storeFile(this
      .enCodingRemoteFilePath(remoteFilePath), localIn);
    // boolean result=ftp.storeFile(remoteFilePath,localIn);
    if (!result) {
     throw new Exception("文件上传失败!");
    }
   } catch (Exception ex) {
    throw ex;
   } finally {
    this.disconnectFtpServer(ftp);
   }
}
  /**
   * 下载
   *
   * @throws Exception
   */
public void download(OutputStream localOut, String remoteFilePath)
    throws Exception {
   FTPClient ftp = this.connectFtpServer();
  try {
    boolean result = ftp.retrieveFile(this
      .enCodingRemoteFilePath(remoteFilePath), localOut);
    // boolean result=ftp.storeFile(remoteFilePath,localIn);
    if (!result) {
     throw new Exception("文件上传失败!");
    }
   } catch (Exception ex) {
    throw ex;
   } finally {
    this.disconnectFtpServer(ftp);
   }
}
  /**
   * 上传结束以后关闭输入流
   *
   * @param localIn
   * @param remoteFilePath
   * @param afterUploadCloseInputStream
   * @throws Exception
   * @throws FtpException
   */
public void upload(InputStream localIn, String remoteFilePath,
    boolean afterUploadCloseInputStream) throws Exception {
   try {
    // 上传
    this.upload(localIn, remoteFilePath);
   } finally {
    if (afterUploadCloseInputStream) {
     if (localIn != null) {
      try {
       localIn.close();
      } catch (Exception ex) {
       throw ex;
      }
     }
    }
   }
}
  /**
   * 得到配置
   *
   * @return
   */
protected FTPClientConfig getFTPClientConfig() {
   // 创建配置对象
   FTPClientConfig conf = new FTPClientConfig(this.config.getProperty(
     "systemKey", FTPClientConfig.SYST_NT));
   conf.setServerLanguageCode(this.config.getProperty(
     "serverLanguageCode", "zh"));
   return conf;
}
  /**
   * 远程文件路径编码(上传到ftp上的文件路径)
   *
   * @param remoteFilePath
   * @return
   * @throws UnsupportedEncodingException
   */
protected String enCodingRemoteFilePath(String remoteFilePath)
    throws UnsupportedEncodingException {
   // return StringUtils.gbkToIso8859EnCoding(remoteFilePath);
   return new String(remoteFilePath.getBytes("gbk"), "ISO8859-1");
  }
  public Properties getConfig() {
   return config;
}
  public void setConfig(Properties config) {
   this.config = config;
}
  }
  package isale.ftp.test;
  import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
  import org.apache.commons.net.ftp.FTPClientConfig;
  public class FtpMain {
public static void main(String[] args) {
/*   //完成上传功能
   FtpClientCommonNetImpl fccn = new FtpClientCommonNetImpl();
   Properties properties=new Properties();
   properties.setProperty("systemKey",FTPClientConfig.SYST_NT);
   properties.setProperty("serverLanguageCode","zh");
   InputStream is = null;
   try {
    is = new FileInputStream("D:/Javascript权威指南/中国IT认证实验室学习下载频道.txt");
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
   properties.setProperty("server","192.168.0.3");
   properties.setProperty("userName","isale");
   properties.setProperty("password","isale");
   fccn.setConfig(properties);
    try {
    fccn.upload(is, "/bugzillaBackup/javacript.java",true);
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }*/
 
//   完成下载功能
   FtpClientCommonNetImpl fccn = new FtpClientCommonNetImpl();
   Properties properties=new Properties();
   properties.setProperty("systemKey",FTPClientConfig.SYST_NT);
   properties.setProperty("serverLanguageCode","zh");
   OutputStream os = null;
   try {
    os = new FileOutputStream("E:/中国IT认证实验室学习下载频道.txt");
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
   properties.setProperty("server","192.168.0.3");
   properties.setProperty("userName","isale");
   properties.setProperty("password","isale");
   fccn.setConfig(properties);
    try {
    fccn.download(os, "/bugzillaBackup/javacript.java");
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
 
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-227567-1-1.html 上篇帖子: FTP上传日志 下篇帖子: SHELL下FTP的一段代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表