package woxingwosu;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Properties;
import java.util.TreeSet;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply; /**
* 其实JDK里面也有支持FTP操作的包【jre/lib下的rt.jar】,但是SUN的DOC里面并没有提供相应文档,
* 因为这里面的包,不被官方支持,建议不要使用。我们可以使用第三方提供的包apache.commons。
* apache.commons的包,都有文档,方便使用
* 另外IBM也有提供一个ftp包,我没有用过,有兴趣的可以去研究一下
* @commons-net:http://apache.mirror.phpchina.com/commons/net/binaries/commons-net-1.4.1.zip
* @jakarta-oro:http://mirror.vmmatrix.net/apache/jakarta/oro/source/jakarta-oro-2.0.8.zip
* @commons-io:http://apache.mirror.phpchina.com/commons/io/binaries/commons-io-1.3.2-bin.zip
* @author 我行我素
* @2007-08-03
*/
public class MiniFtp {
private static String username;
private static String password;
private static String ip;
private static int port;
private static Properties property=null;//配置
private static String configFile;//配置文件的路径名 private static FTPClient ftpClient=null;
private static SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm"); private static final String [] FILE_TYPES={"文件","目录","符号链接","未知类型"}; public static void main(String[] args) {
setConfigFile("woxingwosu.properties");//设置配置文件路径
connectServer();
listAllRemoteFiles();//列出所有文件和目录
changeWorkingDirectory("webroot");//进入文件夹webroot
listRemoteFiles("*.jsp");//列出webroot目录下所有jsp文件
setFileType(FTP.BINARY_FILE_TYPE);//设置传输二进制文件
uploadFile("woxingwosu.xml","myfile.xml");//上传文件woxingwosu.xml,重新命名为myfile.xml
renameFile("viewDetail.jsp", "newName.jsp");//将文件viewDetail.jsp改名为newName.jsp
deleteFile("UpdateData.class");//删除文件UpdateData.class
loadFile("UpdateData.java","loadFile.java");//下载文件UpdateData.java,并且重新命名为loadFile.java
closeConnect();//关闭连接
} /**
* 上传文件
* @param localFilePath--本地文件路径
* @param newFileName--新的文件名
*/
public static void uploadFile(String localFilePath,String newFileName){
connectServer();
//上传文件
BufferedInputStream buffIn=null;
try{
buffIn=new BufferedInputStream(new FileInputStream(localFilePath));
ftpClient.storeFile(newFileName, buffIn);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(buffIn!=null)
buffIn.close();
}catch(Exception e){
e.printStackTrace();
}
}
} /**
* 下载文件
* @param remoteFileName --服务器上的文件名
* @param localFileName--本地文件名
*/
public static void loadFile(String remoteFileName,String localFileName){
connectServer();
//下载文件
BufferedOutputStream buffOut=null;
try{
buffOut=new BufferedOutputStream(new FileOutputStream(localFileName));
ftpClient.retrieveFile(remoteFileName, buffOut);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(buffOut!=null)
buffOut.close();
}catch(Exception e){
e.printStackTrace();
}
}
} /**
* 列出服务器上所有文件及目录
*/
public static void listAllRemoteFiles(){
listRemoteFiles("*");
} /**
* 列出服务器上文件和目录
* @param regStr --匹配的正则表达式
*/
@SuppressWarnings("unchecked")
public static void listRemoteFiles(String regStr){
connectServer();
try{
FTPFile[] files=ftpClient.listFiles(regStr);
if(files==null||files.length==0)
System.out.println("There has not any file!");
else{
TreeSet<FTPFile> fileTree=new TreeSet(
new Comparator(){
//先按照文件的类型排序(倒排),然后按文件名顺序排序
public int compare(Object objFile1,Object objFile2){
if(objFile1==null)
return -1;
else if(objFile2==null)
return 1;
else{
FTPFile file1=(FTPFile)objFile1;
FTPFile file2=(FTPFile)objFile2;
if(file1.getType()!=file2.getType())
return file2.getType()-file1.getType();
else
return file1.getName().compareTo(file2.getName());
}
}
}
);
for(FTPFile file:files)
fileTree.add(file);
System.out.printf("%-35s%-10s%15s%15s\n","名称","类型","修改日期","大小");
for(FTPFile file:fileTree){
System.out.printf("%-35s%-10s%15s%15s\n",iso8859togbk(file.getName()),FILE_TYPES[file.getType()]
,dateFormat.format(file.getTimestamp().getTime()),FileUtils.byteCountToDisplaySize(file.getSize()));
}
}
}catch(Exception e){
e.printStackTrace();
}
} /**
* 关闭连接
*/
public static void closeConnect(){
try{
if(ftpClient!=null){
ftpClient.logout();
ftpClient.disconnect();
}
}catch(Exception e){
e.printStackTrace();
}
} /**
* 设置配置文件
* @param configFile
*/
public static void setConfigFile(String configFile) {
MiniFtp.configFile = configFile;
} /**
* 设置传输文件的类型[文本文件或者二进制文件]
* @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE
*/
public static void setFileType(int fileType){
try{
connectServer();
ftpClient.setFileType(fileType);
}catch(Exception e){
e.printStackTrace();
}
} /**
* 扩展使用
* @return
*/
protected static FTPClient getFtpClient(){
connectServer();
return ftpClient;
} /**
* 设置参数
* @param configFile --参数的配置文件
*/
private static void setArg(String configFile){
property=new Properties();
BufferedInputStream inBuff=null;
try{
inBuff=new BufferedInputStream(new FileInputStream(configFile));
property.load(inBuff);
username=property.getProperty("username");
password=property.getProperty("password");
ip=property.getProperty("ip");
port=Integer.parseInt(property.getProperty("port"));
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(inBuff!=null)
inBuff.close();
}catch(Exception e){
e.printStackTrace();
}
}
} /**
* 连接到服务器
*/
public static void connectServer() {
if (ftpClient == null) {
int reply;
try {
setArg(configFile);
ftpClient=new FTPClient();
ftpClient.setDefaultPort(port);
ftpClient.configure(getFtpConfig());
ftpClient.connect(ip);
ftpClient.login(username, password);
ftpClient.setDefaultPort(port);
System.out.print(ftpClient.getReplyString());
reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
}
} catch (Exception e) {
System.err.println("登录ftp服务器【"+ip+"】失败");
e.printStackTrace();
}
}
} /**
* 进入到服务器的某个目录下
* @param directory
*/
public static void changeWorkingDirectory(String directory){
try{
connectServer();
ftpClient.changeWorkingDirectory(directory);
}catch(IOException ioe){
ioe.printStackTrace();
}
} /**
* 返回到上一层目录
*/
public static void changeToParentDirectory(){
try{
connectServer();
ftpClient.changeToParentDirectory();
}catch(IOException ioe){
ioe.printStackTrace();
}
} /**
* 删除文件
*/
public static void deleteFile(String filename){
try{
connectServer();
ftpClient.deleteFile(filename);
}catch(IOException ioe){
ioe.printStackTrace();
}
} /**
* 重命名文件
* @param oldFileName --原文件名
* @param newFileName --新文件名
*/
public static void renameFile(String oldFileName,String newFileName){
try{
connectServer();
ftpClient.rename(oldFileName, newFileName);
}catch(IOException ioe){
ioe.printStackTrace();
}
} /**
* 设置FTP客服端的配置--一般可以不设置
* @return
*/
private static FTPClientConfig getFtpConfig(){
FTPClientConfig ftpConfig=new FTPClientConfig(FTPClientConfig.SYST_UNIX);
ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
return ftpConfig;
} /**
* 转码[ISO-8859-1 -> GBK]
*不同的平台需要不同的转码
* @param obj
* @return
*/
private static String iso8859togbk(Object obj){
try{
if(obj==null)
return "";
else
return new String(obj.toString().getBytes("iso-8859-1"),"GBK");
}catch(Exception e){
return "";
}
}
}

本文转自:http://www.cnblogs.com/wanghafan/archive/2012/12/04/2801758.html

Java 利用Apache Commons Net 实现 FTP文件上传下载的更多相关文章

  1. Python 基于Python实现Ftp文件上传,下载

    基于Python实现Ftp文件上传,下载   by:授客 QQ:1033553122 测试环境: Ftp客户端:Windows平台 Ftp服务器:Linux平台 Python版本:Python 2.7 ...

  2. java/struts/Servlet文件下载与ftp文件上传下载

    1.前端代码 使用超链接到Struts的Action或Servlet <a target="_blank" href="ftpFileAction!download ...

  3. Java使用comms-net jar包完成ftp文件上传进度的检测功能

    本文章只讲述大致的思路与本次功能对应的一些开发环境,具体实现请结合自己的开发情况,仅供参考,如果有不对的地方,欢迎大家指出! 准备环境:JDK1.7 OR 1.8.eclipse.ftp服务器(可自行 ...

  4. 【FTP】FTP文件上传下载-支持断点续传

    Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...

  5. java实现ftp文件上传下载,解决慢,中文乱码,多个文件下载等问题

    //文件上传 public static boolean uploadToFTP(String url,int port,String username,String password,String ...

  6. python 实现远端ftp文件上传下载

    python 实现ftp上传下载 * 脚本需要传入两个参数,参数1为需要从远端ftp站点下载文件名称,参数2为已知需要下载的文件md5值,文件下载完成后会自动进行md5值校验 * 运行示例 [root ...

  7. 4.1 - FTP文件上传下载

    题目:开发一个支持多用户同时在线的FTP程序要求:1.用户加密认证2.允许同时多用户登录3.每个用户有自己的家目录,且只能访问自己的家目录4.对用户进行磁盘配额,每个用户的可用空间不同5.允许用户在f ...

  8. ftp文件上传下载命令

    介绍:从本地以用户wasqry登录的机器1*.1**.21.67上通过ftp远程登录到ftp服务器上,登录用户名是lte****,以下为使用该连接做的实验.  查看远程ftp服务器上用户lte**** ...

  9. FTP文件上传下载

    使用Apache Commons Net来实现FTP服务器文件的上传 与 下载 maven配置Jar <!-- https://mvnrepository.com/artifact/common ...

随机推荐

  1. 《ASP.NET MVC4 WEB编程》学习笔记------UrlHelper

    HtmlHelper帮助我们生成Html标记代码:UrlHelper帮助我们生成URL链接地址 我们学习一下UrlHelper帮助类,看类名也都知道这个类是用来帮我们生成URL在ASP.NET MVC ...

  2. PYTHON实现HTTP摘要认证(DIGEST AUTHENTICATION)

    参考: http://blog.csdn.net/kiwi_coder/article/details/28677651 http://blog.csdn.net/gl1987807/article/ ...

  3. nginx服务器的网站权限问题

    有时候我们的网站根目录会从一个目录迁移到另一个目录,如果我们服务器使用的是nginx或者Apache,我们一般会配置好网站根目录后然后往直接把网站解压或者上传到根目录中,这样引起的问题是无法对对文件进 ...

  4. 1.django笔记之django基础

    一.django简介 Django是一个开放源代码的Web应用框架,由Python写成.采用了MVC的软件设计模式,即模型M,视图V和控制器C.它最初是被开发来用于管理劳伦斯出版集团旗下的一些以新闻内 ...

  5. JsRender语法

    {{:#data.Name}} 或 {{:Name}} 直接显示html格式{{>#data.Name}} 或 {{>Name}} 转义显示html字符 if else {{if bool ...

  6. NEFU 1142 表哥的面包

    表哥的面包 Problem:1142 Time Limit:1000ms Memory Limit:65535K Description 可爱的表哥遇到了一个问题,有一个长为N(1≤N≤10^18)的 ...

  7. Shopping(hdu 3768)

    题意:给你一个无向图,求从0号点开始遍历所有的指定点再回到0号点的最短路径 #include<cstdio> #include<iostream> #include<qu ...

  8. Android实现电子邮箱客户端

    本文主要讲述了安卓平台上利用QQ邮箱SMTP协议,POP3协议发送与接收消息的实现 发送邮件核心代码 import java.security.Security; import java.util.D ...

  9. MakeFile中赋值

    Makefile 中:= ?= += =的区别   在Makefile中我们经常看到 = := ?= +=这几个赋值运算符,那么他们有什么区别呢?我们来做个简单的实验 新建一个Makefile,内容为 ...

  10. 如何从Apache官网下载windows版apache服务器

    参考文章:http://jingyan.baidu.com/article/29697b912f6539ab20de3cf8.html