最近做了一個通過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功能就行啦!