java实现ftp文件的上传与下载
生活随笔
收集整理的這篇文章主要介紹了
java实现ftp文件的上传与下载
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
最近在做ftp文件的上傳與下載,基于此,整理了一下資料。本來想采用java自帶的方法,可是看了一下jdk1.6與1.7的實(shí)現(xiàn)方法有點(diǎn)區(qū)別,于是采用了Apache下的框架實(shí)現(xiàn)的。。。
1.首先引用3個包
?
2.然后是相關(guān)類的代碼
/*** ftp鏈接常量**/ public class Ftp {private String ipAddr;//ip地址private Integer port;//端口號private String userName;//用戶名private String pwd;//密碼private String path;//aaa路徑public String getIpAddr() {return ipAddr;}public void setIpAddr(String ipAddr) {this.ipAddr = ipAddr;}public Integer getPort() {return port;}public void setPort(Integer port) {this.port = port;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getPath() {return path;}public void setPath(String path) {this.path = path;}} import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream;import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.apache.log4j.Logger;public class FtpUtil {private static Logger logger=Logger.getLogger(FtpUtil.class);private static FTPClient ftp;/*** 獲取ftp連接* @param f* @return* @throws Exception*/public static boolean connectFtp(Ftp f) throws Exception{ftp=new FTPClient();boolean flag=false;int reply;if (f.getPort()==null) {ftp.connect(f.getIpAddr(),21);}else{ftp.connect(f.getIpAddr(),f.getPort());}ftp.login(f.getUserName(), f.getPwd());ftp.setFileType(FTPClient.BINARY_FILE_TYPE);reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return flag; } ftp.changeWorkingDirectory(f.getPath()); flag = true; return flag;}/*** 關(guān)閉ftp連接*/public static void closeFtp(){if (ftp!=null && ftp.isConnected()) {try {ftp.logout();ftp.disconnect();} catch (IOException e) {e.printStackTrace();}}}/*** ftp上傳文件* @param f* @throws Exception*/public static void upload(File f) throws Exception{if (f.isDirectory()) {ftp.makeDirectory(f.getName());ftp.changeWorkingDirectory(f.getName());String[] files=f.list();for(String fstr : files){File file1=new File(f.getPath()+"/"+fstr);if (file1.isDirectory()) {upload(file1);ftp.changeToParentDirectory();}else{File file2=new File(f.getPath()+"/"+fstr);FileInputStream input=new FileInputStream(file2);ftp.storeFile(file2.getName(),input);input.close();}}}else{File file2=new File(f.getPath());FileInputStream input=new FileInputStream(file2);ftp.storeFile(file2.getName(),input);input.close();}}/*** 下載鏈接配置* @param f* @param localBaseDir 本地目錄* @param remoteBaseDir 遠(yuǎn)程目錄* @throws Exception*/public static void startDown(Ftp f,String localBaseDir,String remoteBaseDir ) throws Exception{if (FtpUtil.connectFtp(f)) {try { FTPFile[] files = null; boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); if (changedir) { ftp.setControlEncoding("GBK"); files = ftp.listFiles(); for (int i = 0; i < files.length; i++) { try{ downloadFile(files[i], localBaseDir, remoteBaseDir); }catch(Exception e){ logger.error(e); logger.error("<"+files[i].getName()+">下載失敗"); } } } } catch (Exception e) { logger.error(e); logger.error("下載過程中出現(xiàn)異常"); } }else{logger.error("鏈接失敗!");}}/** * * 下載FTP文件 * 當(dāng)你需要下載FTP文件的時(shí)候,調(diào)用此方法 * 根據(jù)<b>獲取的文件名,本地地址,遠(yuǎn)程地址</b>進(jìn)行下載 * * @param ftpFile * @param relativeLocalPath * @param relativeRemotePath */ private static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) { if (ftpFile.isFile()) {if (ftpFile.getName().indexOf("?") == -1) { OutputStream outputStream = null; try { File locaFile= new File(relativeLocalPath+ ftpFile.getName()); //判斷文件是否存在,存在則返回 if(locaFile.exists()){ return; }else{ outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName()); ftp.retrieveFile(ftpFile.getName(), outputStream); outputStream.flush(); outputStream.close(); } } catch (Exception e) { logger.error(e);} finally { try { if (outputStream != null){ outputStream.close(); }} catch (IOException e) { logger.error("輸出文件流異常"); } } } } else { String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString()); File fl = new File(newlocalRelatePath); if (!fl.exists()) { fl.mkdirs(); } try { newlocalRelatePath = newlocalRelatePath + '/'; newRemote = newRemote + "/"; String currentWorkDir = ftpFile.getName().toString(); boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); if (changedir) { FTPFile[] files = null; files = ftp.listFiles(); for (int i = 0; i < files.length; i++) { downloadFile(files[i], newlocalRelatePath, newRemote); } } if (changedir){ftp.changeToParentDirectory(); } } catch (Exception e) { logger.error(e);} } } public static void main(String[] args) throws Exception{ Ftp f=new Ftp();f.setIpAddr("1111");f.setUserName("root");f.setPwd("111111");FtpUtil.connectFtp(f);File file = new File("F:/test/com/test/Testng.java"); FtpUtil.upload(file);//把文件上傳在ftp上FtpUtil.startDown(f, "e:/", "/xxtest");//下載ftp文件測試System.out.println("ok");} }以上代碼均測試通過了。。。
?
?
?
?
?
項(xiàng)目及相關(guān)包下載:http://pan.baidu.com/s/1hq5p7NI
文章來源:http://www.cnblogs.com/huzi007/p/4236150.html
轉(zhuǎn)載于:https://www.cnblogs.com/lr393993507/p/5502266.html
總結(jié)
以上是生活随笔為你收集整理的java实现ftp文件的上传与下载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VMware10.0.4下 CentOS
- 下一篇: 【bzoj3631】[JLOI2014]