当前位置:   article > 正文

ftp list 空 java,commons.net包中的FTPClient.listFiles()方法返回null的问...JAVA中使用FTPClient上传下载...

timestamp could not be parsed with older or recent dateformat

commons-net-1.4.1.jar包中ftp应用的几点问题

一、异常:

从http://commons.apache.com/网站下载了commons-net-1.4.1包后添加到自己的工程中,调用FtpClient类的listFiles(String pathName)方法时,抛如下异常:

Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/oro/text/regex/MalformedPatternException

at org.apache.commons.net.ftp.parser.RegexFTPFileEntryParserImpl. (RegexFTPFileEntryParserImpl.java:75)

at org.apache.commons.net.ftp.parser.ConfigurableFTPFileEntryParserImpl.(ConfigurableFTPFileEntryParserImpl.java:57)

at org.apache.commons.net.ftp.parser.UnixFTPEntryParser.(UnixFTPEntryParser.java:136)

at org.apache.commons.net.ftp.parser.UnixFTPEntryParser.(UnixFTPEntryParser.java:119)

at  org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createUnixFTPEntryParser(DefaultFTPFileEntryParserFactory.java:169)

at org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createFileEntryParser(DefaultFTPFileEntryParserFactory.java:94)

at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:2358)

at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2141)

at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2188)

.................

以上异常是由于缺少辅助的包jakarta-oro-2.0.8.jar引起的,去http://commons.apache.com/网站下载该包后放入工程的lib下,并加载到classpath中,重新编译运行,OK!

二、调用FtpClient类的listFiles(String pathName)方法失效的问题:

一般是由于ftp服务器(主要是小型机)的操作系统不同语言环境的时间格式造成的,在中文环境下,文件或文件夹的时间格式为"m月d日 hh:mm"或"yyyy年m月 d",而E文环境下时间格式为"MMM d yyyy"或"MMM d HH:mm",于是,在中文环境下,ftp包中的FTPTimestampParserImpl类将时间字符串Date化时抛异常,因为commons-net-1.4.1包不支持中文。

解决办法(两种办法):

1. 将ftp服务器操作系统语言环境设为英文;

2. 修改ftp包的代码:将FTPTimestampParserImpl类进行扩展,使之支持中文

下面针对第2种解决办法来实现:

(1)    新建类FTPTimestampParserImplExZH类:

1

22436270_2.gif/**222436270_3.gif* FTPTimestampParserImpl的扩展类,使之支持中文环境的时间格式322436270_3.gif* Date:2007-8-15422436270_6.gif*/522436270_1.gifpackageorg.apache.commons.net.ftp.parser;622436270_1.gif722436270_1.gifimportjava.text.ParseException;822436270_1.gifimportjava.text.ParsePosition;922436270_1.gifimportjava.text.SimpleDateFormat;1022436270_1.gifimportjava.util.Calendar;1122436270_1.gifimportjava.util.Date;1222436270_1.gif1322436270_2.gif/**1422436270_3.gif*@authorhzwei2061522436270_3.gif* FTPTimestampParserImpl的扩展类,使之支持中文环境的时间格式1622436270_6.gif*/1722436270_1.gifpublicclassFTPTimestampParserImplExZHextendsFTPTimestampParserImpl1822436270_2.gif{1922436270_3.gifprivateSimpleDateFormat defaultDateFormat=newSimpleDateFormat("mm d hh:mm");2022436270_3.gifprivateSimpleDateFormat recentDateFormat=newSimpleDateFormat("yyyy mm d");2122436270_3.gif2222436270_4.gif/**2322436270_3.gif       *@authorhzwei2062422436270_3.gif       * 将中文环境的时间格式进行转换2522436270_5.gif*/2622436270_3.gifprivateString formatDate_Zh2En(String timeStrZh)2722436270_4.gif{2822436270_3.gifif(timeStrZh==null)2922436270_4.gif{3022436270_3.gifreturn"";3122436270_5.gif          }3222436270_3.gif3322436270_3.gifintlen=timeStrZh.length();3422436270_3.gif          StringBuffer sb=newStringBuffer(len);3522436270_3.gifcharch='';3622436270_3.giffor(inti=0;i{3822436270_3.gif              ch=timeStrZh.charAt(i);3922436270_3.gifif((ch>='0'&&ch<='9')||ch==''||ch==':')4022436270_4.gif{4122436270_3.gif                  sb.append(ch);4222436270_5.gif              }4322436270_5.gif          }4422436270_3.gif4522436270_3.gifreturnsb.toString();4622436270_5.gif      }4722436270_3.gif4822436270_4.gif/**4922436270_3.gif       * Implements the one {@linkFTPTimestampParser#parseTimestamp(String)    method}5022436270_3.gif       * in the {@linkFTPTimestampParser    FTPTimestampParser} interface5122436270_3.gif       * according to this algorithm:5222436270_3.gif       *5322436270_3.gif       * If the recentDateFormat member has been defined, try to parse the5422436270_3.gif       * supplied string with that.    If that parse fails, or if the recentDateFormat5522436270_3.gif       * member has not been defined, attempt to parse with the defaultDateFormat5622436270_3.gif       * member.    If that fails, throw a ParseException.5722436270_3.gif       *5822436270_3.gif       *@seeorg.apache.commons.net.ftp.parser.FTPTimestampParser#parseTimestamp(java.lang.String)5922436270_5.gif*/6022436270_3.gifpublicCalendar parseTimestamp(String timestampStr)throwsParseException6122436270_4.gif{6222436270_3.gif          timestampStr=formatDate_Zh2En(timestampStr);6322436270_3.gif          Calendar now=Calendar.getInstance();6422436270_3.gif          now.setTimeZone(this.getServerTimeZone());6522436270_3.gif6622436270_3.gif          Calendar working=Calendar.getInstance();6722436270_3.gif          working.setTimeZone(this.getServerTimeZone());6822436270_3.gif          ParsePosition pp=newParsePosition(0);6922436270_3.gif7022436270_3.gif          Date parsed=null;7122436270_3.gifif(this.recentDateFormat!=null)7222436270_4.gif{7322436270_3.gif              parsed=recentDateFormat.parse(timestampStr, pp);7422436270_5.gif          }7522436270_3.gifif(parsed!=null&&pp.getIndex()==timestampStr.length())7622436270_4.gif{7722436270_3.gif              working.setTime(parsed);7822436270_3.gif              working.set(Calendar.YEAR, now.get(Calendar.YEAR));7922436270_3.gifif(working.after(now))8022436270_4.gif{8122436270_3.gif                  working.add(Calendar.YEAR,-1);8222436270_5.gif              }8322436270_5.gif          }8422436270_3.gifelse8522436270_4.gif{8622436270_3.gif              pp=newParsePosition(0);8722436270_3.gif              parsed=defaultDateFormat.parse(timestampStr, pp);8822436270_3.gif//note, length checks are mandatory for us since8922436270_3.gif//SimpleDateFormat methods will succeed if less than9022436270_3.gif//full string is matched. They will also accept,9122436270_3.gif//despite "leniency" setting, a two-digit number as9222436270_3.gif//a valid year (e.g. 22:04 will parse as 22 A.D.)9322436270_3.gif//so could mistakenly confuse an hour with a year,9422436270_3.gif//if we don't insist on full length parsing.9522436270_3.gifif(parsed!=null&&pp.getIndex()==timestampStr.length())9622436270_4.gif{9722436270_3.gif                  working.setTime(parsed);9822436270_5.gif              }9922436270_3.gifelse10022436270_4.gif{10122436270_3.gifthrownewParseException(10222436270_3.gif"Timestamp could not be parsed with older or recent DateFormat",10322436270_3.gif                          pp.getIndex());10422436270_5.gif              }10522436270_5.gif          }10622436270_3.gifreturnworking;10722436270_5.gif      }10822436270_6.gif}10922436270_1.gif11022436270_1.gif11122436270_1.gif

(2)修改org.apache.commons.net.ftp.parser.UnixFTPEntryParser类的parseFTPEntry方法:

1

22436270_1.gifpublicFTPFile parseFTPEntry(String entry)222436270_2.gif{322436270_3.gif          

22436270_7.gif

22436270_7.gif..422436270_3.gifif(matches(entry))522436270_4.gif{622436270_3.gif              String typeStr=group(1);722436270_3.gif              String hardLinkCount=group(15);822436270_3.gif              String usr=group(16);922436270_3.gif              String grp=group(17);1022436270_3.gif              String filesize=group(18);1122436270_3.gif              String datestr=group(19)+""+group(20);1222436270_3.gif              String name=group(21);1322436270_3.gif              String endtoken=group(22);1422436270_3.gif1522436270_3.giftry1622436270_4.gif{1722436270_3.gif                  file.setTimestamp(super.parseTimestamp(datestr));1822436270_5.gif              }1922436270_3.gifcatch(ParseException e)2022436270_4.gif{2122436270_4.gif/****mod by hzwei206 将中文时间格式转换 2007-8-15 begin****/2222436270_3.gif//return null;//this is a parsing failure too.2322436270_3.giftry2422436270_4.gif{2522436270_3.gif                      FTPTimestampParserImplExZH Zh2En=newFTPTimestampParserImplExZH();2622436270_3.gif                      file.setTimestamp(Zh2En.parseTimestamp(datestr));2722436270_5.gif                  }2822436270_3.gifcatch(ParseException e1)2922436270_4.gif{3022436270_3.gifreturnnull;//this is a parsing failure too.3122436270_5.gif}3222436270_4.gif/****mod by hzwei206 将中文时间格式转换 2007-8-15 end****/3322436270_5.gif              }3422436270_3.gif3522436270_3.gif              

22436270_7.gif

22436270_7.gif

22436270_7.gif

22436270_7.gif

22436270_7.gif..3622436270_5.gif      }3722436270_3.gif

JAVA中使用FTPClient上传下载

在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件。

一、上传文件

原理就不介绍了,大家直接看代码吧

/**

* Description: 向FTP服务器上传文件

* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保(cuihongbao@d-heaven.com)创建

* @param url FTP服务器hostname

* @param port FTP服务器端口

* @param username FTP登录账号

* @param password FTP登录密码

* @param path FTP服务器保存目录

* @param filename 上传到FTP服务器上的文件名

* @param input 输入流

* @return 成功返回true,否则返回false

*/

publicstaticbooleanuploadFile(String url,intport,String username, String password, String path, String filename, InputStream input) {

booleansuccess =false;

FTPClient ftp = newFTPClient();

try{

intreply;

ftp.connect(url, port);//连接FTP服务器

//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器

ftp.login(username, password);//登录

reply = ftp.getReplyCode();

if(!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect();

returnsuccess;

}

ftp.changeWorkingDirectory(path);

ftp.storeFile(filename, input);

input.close();

ftp.logout();

success = true;

} catch(IOException e) {

e.printStackTrace();

} finally{

if(ftp.isConnected()) {

try{

ftp.disconnect();

} catch(IOException ioe) {

}

}

}

returnsuccess;

}

 
 

下面我们写两个小例子:

1.将本地文件上传到FTP服务器上,代码如下:

@Test

publicvoidtestUpLoadFromDisk(){

try{

FileInputStream in=newFileInputStream(newFile("D:/test.txt"));

booleanflag = uploadFile("127.0.0.1",21,"test","test","D:/ftp","test.txt", in);

System.out.println(flag);

} catch(FileNotFoundException e) {

e.printStackTrace();

}

}

 
 

2.在FTP服务器上生成一个文件,并将一个字符串写入到该文件中

@Test

publicvoidtestUpLoadFromString(){

try{

InputStream input = newByteArrayInputStream("test ftp".getBytes("utf-8"));

booleanflag = uploadFile("127.0.0.1",21,"test","test","D:/ftp","test.txt", input);

System.out.println(flag);

} catch(UnsupportedEncodingException e) {

e.printStackTrace();

}

}

 
 

二、下载文件

从FTP服务器下载文件的代码也很简单,参考如下:

/**

* Description: 从FTP服务器下载文件

* @Version1.0 Jul 27, 2008 5:32:36 PM by 崔红保(cuihongbao@d-heaven.com)创建

* @param url FTP服务器hostname

* @param port FTP服务器端口

* @param username FTP登录账号

* @param password FTP登录密码

* @param remotePath FTP服务器上的相对路径

* @param fileName 要下载的文件名

* @param localPath 下载后保存到本地的路径

* @return

*/

publicstaticbooleandownFile(String url,intport,String username, String password, String remotePath,String fileName,String localPath) {

booleansuccess =false;

FTPClient ftp = newFTPClient();

try{

intreply;

ftp.connect(url, port);

//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器

ftp.login(username, password);//登录

reply = ftp.getReplyCode();

if(!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect();

returnsuccess;

}

ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录

FTPFile[] fs = ftp.listFiles();

for(FTPFile ff:fs){

if(ff.getName().equals(fileName)){

File localFile = newFile(localPath+"/"+ff.getName());

OutputStream is = newFileOutputStream(localFile);

ftp.retrieveFile(ff.getName(), is);

is.close();

}

}

ftp.logout();

success = true;

} catch(IOException e) {

e.printStackTrace();

} finally{

if(ftp.isConnected()) {

try{

ftp.disconnect();

} catch(IOException ioe) {

}

}

}

returnsuccess;

}

 
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/255554
推荐阅读
相关标签
  

闽ICP备14008679号