最近做了一个通过JAVA从FTP服务器上下载文件并解析文件的小功能,自己通过找资料做了出来,这里做出总结.
这是一个,模拟FTP服务器的软件,用来测试功能.
1.要连接FTP服务器需要的要素有这些:IP地址,端口号(默认21),用户名,密码.
不多说直接上代码,带上注释要好理解点!
/**从FTP下载文件*/ public static List<PrpJFOrder> downFile(String url, int port,String username, String password, String fileName,String localPath,String movePath,String ftpPath){//fileName:用来指定某些文件 movePath:这里是用来备份文件的路径,正常场景下都需要备份 localPath:下载下来的路径,一般解析完之后就复制到备份文件的路径然后删除 ftpPath:一般FTP服务器会指向一个根目录,而我们的文件不一定在根目录,所以需要到某个路径下寻找文件 FTPClient ftp = new FTPClient();//创建连接FTP类,这个类需要commons-net-3.3.jar包的支持 List<PrpJFOrder> readFile = null;//这是我要解析的文件需要存到某个对象中,无须关注 try { int reply; ftp.connect(url,port);//连接端口与IP if(!ftp.login(username, password)){ System.out.println("登陆FTP用户或密码错误");//登陆 } reply = ftp.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)){ ftp.disconnect();//连接失败 System.out.println("连接失败"); return null; } ftp.changeWorkingDirectory(ftpPath);//指定FTP文件目录 //转移到FTP服务器目录 FTPFile[] fs = ftp.listFiles();//服务器目录下所有文件 for(FTPFile ff:fs){//遍历这些文件查找符合条件的文件 if(ff.getName().indexOf(fileName)!=-1 && ff.getName().indexOf("yx")!=-1){//遍历到当前文件如果包含日期字符串 File localFile = new File(localPath+File.separator+ff.getName()); OutputStream os = new FileOutputStream(localFile); ftp.retrieveFile(ff.getName(), os); //解析文件下载下来的文件 readFile = readFile(localPath+File.separator+ff.getName()); //解析完毕将文件移到指定目录-->复制+删除 if(localFile.exists()){ File file = new File(movePath+File.separator+ff.getName());//移动的目录 FileInputStream fis = new FileInputStream(localFile); FileOutputStream fos = new FileOutputStream(file); byte[] buff = new byte[1024]; int length; while((length=fis.read(buff))>0){ fos.write(buff, 0, length); } //删除原文件 fis.close(); fos.close(); } if(os!=null){ os.close(); } localFile.delete(); } } ftp.logout(); } catch (IOException e) { e.printStackTrace(); }finally{ if(ftp.isConnected()){ try{ ftp.disconnect(); }catch(IOException ioe){ ioe.printStackTrace(); } } } return readFile; }
上面的代码涉及到解析文件的可以不用关注哟,关注主要连接FTP功能就行啦!