【IT168技术文档】
要在项目里实现用ftp下载文件. 遇到了很多问题. 于是我推荐他用Jakarta-Commons项目中的net组件在实现. 其实之前我也没有实际用过, 稍稍看了一下文档,知道里面有个ftp包能完成相关的操作. 于是我的同事就兴致勃勃的拿去用了. 可用了以后才发现有很多问题, 搞得焦头烂额. 经过我们的努力, 终于把问题都解决了, 下面我把遇到的问题和解决方案写下来, 以备其他想要用common-net包的朋友参考.
首先把代码贴出来:
public class ClientTest { 2 public static void main(String[] args) { 3 String url = "172.17.1.38"; 4 String user = "test"; 5 String pwd = "test"; 6 7 FTPClient ftp = new FTPClient(); 8 ftp.setControlEncoding("GBK"); 9 FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); 10 conf.setServerLanguageCode("zh"); 11 ftp.configure(conf); 12 13 try { 14 ftp.connect(url); 15 if (ftp.login(user, pwd)) { 16 int reply = ftp.getReplyCode(); 17 if (!FTPReply.isPositiveCompletion(reply)) { 18 ftp.disconnect(); 19 System.out.println("disconnect"); 20 } else { 21 ftp.enterLocalPassiveMode(); 22 ftp.setFileType(FTP.BINARY_FILE_TYPE); 23 24 File dir = new File("down"); 25 if (!dir.exists()) { 26 dir.mkdirs(); 27 } 28 29 String[] names = ftp.listNames(); 30 for (String name : names) { 31 File file = new File(dir.getPath() + File.separator + name); 32 if (!file.exists()) { 33 file.createNewFile(); 34 } 35 long pos = file.length(); 36 RandomAccessFile raf = new RandomAccessFile(file, "rw"); 37 raf.seek(pos); 38 ftp.setRestartOffset(pos); 39 40 InputStream is = ftp.retrieveFileStream(name); 41 if (is == null) { 42 System.out.println("no such file:" + name); 43 } else { 44 System.out.println("start getting file:" + name); 45 46 int b; 47 while ((b = is.read()) != -1) { 48 raf.write(b); 49 } 50 if (ftp.getReply() == FTPReply.CODE_226) { 51 System.out.println("done!"); 52 } 53 is.close(); 54 } 55 raf.close(); 56 } 57 } 58 ftp.logout(); 59 } 60 } catch (IOException e) { 61 e.printStackTrace(); 62 } 63 } 64 }