FtpClient和FTPClient下载的使用
最近接收一个遗留项目,用的是flex和java,后台用的是mybatis和spring。在测试时发现下载有问题,结果花了一两天时间才将问题解决,下面将解决过程中碰到的问题和解决的思路贴出来:
因为项目做出来有段时间了,当初用的是sun.net.ftp.FtpClient这个类,这个类本身就存在问题,而且java api文档中无法查询。并且是jdk1.6的版本,导致放在jre1.7上时保存,后来改成jre1.6问题才解决,但是仍然无法下载,一直报异常“Source not found for $$FastClassByCGLIB$$7782d62a.invoke(int, Object, Object[]) line: not available”。让人很纠结,硬是没有找到原因所在,网上有的说是sql语句错了,有的说是jar包的问题,有的说是反射或cglib的问题等等,但是一一测试仍然没有解决,因为之前有人说这个功能是好的,所以就没有打算换方法,后来实在不行,网上也有人建议用apache的org.apache.commons.net.ftp.FTPClient类,就换成了FTPClient。结果居然好用了:
代码如下:
public static boolean downFile(List<String> directoryList,String targetPath) { boolean success = false; for (String directoryString : directoryList) { String fileName = directoryString.substring(directoryString.lastIndexOf("/") + 1); String remotePath = directoryString.substring(1, directoryString.lastIndexOf("/")); FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(ftpIP); ftp.login(username, password);//登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录 FTPFile[] fs = ftp.listFiles(); for(FTPFile ff:fs){ if(ff.getName().equals(fileName)){ File localFile = new File(targetPath+"/"); if (!localFile.exists()) { localFile.mkdirs(); } OutputStream is = new FileOutputStream(localFile+"/"+ff.getName()); 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) { } } } } return success; }