JavaFTP文件傳輸 簡單實現

簡單介紹下win7 上配置FTP服務和java實現FTP小練習。

如果是win7系統首先開啓ftp服務 控制面板->程序->打開關閉windows功能如圖:

這裏寫圖片描述


打開ftp服務,然後開始配置ftp服務站點,打開管理服務,如下圖:

這裏寫圖片描述

選擇站點右擊 添加FTP站點如圖:
這裏寫圖片描述

設置屬性按照下面三個步驟就配置好一個本地ftp服務站點非常之簡單 如圖:

這裏寫圖片描述

這裏寫圖片描述

這裏寫圖片描述

好了 FTP服務配置好了如何測試一下呢,這裏先介紹一個FTP客戶端軟件,叫做FileZilla Client 簡稱 fz 一個很強大的FTP客戶端官網地址
下載安裝很簡單就不過多介紹了,看一下安裝好了之後連接剛纔建好的ftp的站點,因爲是創建的匿名站點這裏不需要密碼,實際根據具情況配置站點。


這裏寫圖片描述

測試下自己給自己電腦傳文件,下載文件吧(感覺傻傻的樣子…)。


接下來開始寫有用的java連接TFP站點和傳輸文件的代碼。
1.首先jar用的是apache 的工具包 請自行下載
這裏寫圖片描述

2.倆個文件代碼 一個FtpConfig.java 和 FtpUtil.java 實現了上傳,文件夾下載,和單文件下載 詳情如下均已測試。
FtpConfig.java

/**
 * 
 */
package FTPDemo;

/**
 * @date 2016年12月30日
 * @author xie
 * 
 */
public class FtpConfig {

  // 主機ip
  private String FtpHost;
  // 端口號
  private Integer FtpPort;
  // ftp用戶名
  private String FtpUser;
  // ftp密碼
  private String FtpPassword;
  // ftp中的目錄
  private String FtpPath;

  public String getFtpHost() {
    return FtpHost;

  }

  public Integer getFtpPort() {
    return FtpPort;
  }

  public void setFtpPort(Integer ftpPort) {
    FtpPort = ftpPort;
  }

  public void setFtpHost(String ftpHost) {
    FtpHost = ftpHost;
  }

  public String getFtpUser() {
    return FtpUser;
  }

  public void setFtpUser(String ftpUser) {
    FtpUser = ftpUser;
  }

  public String getFtpPassword() {
    return FtpPassword;
  }

  public void setFtpPassword(String ftpPassword) {
    FtpPassword = ftpPassword;
  }

  public String getFtpPath() {
    return FtpPath;
  }

  public void setFtpPath(String ftpPath) {
    FtpPath = ftpPath;
  }

}

FtpUtil.java

/**
 * 
 */
package FTPDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpUtil { 

private static FTPClient ftp;


/**
 * 獲取ftp連接
 * @param f
 * @return
 * @throws Exception
 */
public static boolean connectFtp(FtpConfig f) throws Exception{
    ftp=new FTPClient();
    boolean flag=false;
    if (f.getFtpPort()==null) {
        ftp.connect(f.getFtpHost(),21);
    }else{
        ftp.connect(f.getFtpHost(),f.getFtpPort());
    }
    ftp.login(f.getFtpUser(), f.getFtpPassword());
    int reply = ftp.getReplyCode();      
    if (!FTPReply.isPositiveCompletion(reply)) {      
          ftp.disconnect();      
          return flag;      
    }      
    ftp.changeWorkingDirectory(f.getFtpPath());      
    flag = true;      
    return flag;
}

/**
 * 關閉ftp連接
 */
public static void closeFtp(){
  try {
      if (ftp!=null && ftp.isConnected()) {
            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()+File.separator+fstr);
            if (file1.isDirectory()) {
                upload(file1);
                ftp.changeToParentDirectory();
            }else{
                File file2=new File(f.getPath()+File.separator+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 遠程目錄
 * @throws Exception
 */
public static void startDownDir(FtpConfig f,String localBaseDir,String remoteBaseDir) throws Exception{
    if (FtpUtil.connectFtp(f)) {
        try { 
            FTPFile[] files = null; 
            boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); 
            if (changedir) { 
                ftp.setControlEncoding("UTF-8"); 
                files = ftp.listFiles(); 
                for (int i = 0; i < files.length; i++) { 
                     downloadFile(files[i], localBaseDir, remoteBaseDir); 
                } 
            }else{
                 System.out.println("不存在的相對路徑!");
            } 
        } catch (Exception e) { 
          e.printStackTrace();
        } 
    }else{
       System.out.println("連接失敗");
    }

}

public static void startDownFile(FtpConfig f,String localBaseDir,String remoteFilePath) throws Exception{
  if (FtpUtil.connectFtp(f)) {
    try { 
      FileOutputStream outputStream = new FileOutputStream(localBaseDir + remoteFilePath); 
      ftp.retrieveFile(remoteFilePath, outputStream);
      outputStream.flush();
      outputStream.close();
    } catch (Exception e) { 
      e.printStackTrace();
    } 
  }else{
    System.out.println("連接FTP服務器失敗");
  }

}


/** 
 * 
 * 下載FTP文件 
 * 當你需要下載FTP文件的時候,調用此方法 
 * 根據<b>獲取的文件名,本地地址,遠程地址</b>進行下載 
 * 
 * @param ftpFile 
 * @param relativeLocalPath 下載到本地的絕對路徑
 * @param relativeRemotePath 要下載的遠程ftp服務器相對路徑
 */ 
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()); 
                //判斷文件是否存在,存在則返回  or 直接覆蓋
                if(locaFile.exists()){ 
                    return; 
                }else{ 
                    outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName()); 
                    ftp.retrieveFile(ftpFile.getName(), outputStream);
                    outputStream.flush(); 
                } 
            } catch (Exception e) { 
                     e.printStackTrace();
            } finally { 
                try { 
                    if (outputStream != null){ 
                        outputStream.close(); 
                    }
                } catch (IOException e) { 
                   e.printStackTrace();
                } 
            } 
        } 
    } else { 
        String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); 
        String newRemote = relativeRemotePath + ftpFile.getName().toString(); 
        File fl = new File(newlocalRelatePath); 
        if (!fl.exists()) { 
            fl.mkdirs(); 
        } 
        try { 
            newlocalRelatePath = newlocalRelatePath+File.separator; 
            newRemote = newRemote+File.separator; 
            String currentWorkDir = ftpFile.getName().toString();
            //System.out.println(currentWorkDir);
            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) { 
            e.printStackTrace();
        } 
    } 
} 


public static void main(String[] args) throws Exception{  
        FtpConfig f=new FtpConfig();
        f.setFtpHost("192.168.3.100");
        f.setFtpPort(21);
        f.setFtpUser("anonymous");
        f.setFtpPassword("");
        // f.setFtpPath("/data1/");//相對路徑
        FtpUtil.connectFtp(f);
        File file = new File("E:\\data1\\physics.txt");

        //FtpUtil.upload(file);//把文件上傳在ftp上
        // FtpUtil.startDownFile(f, "E:/",  "physics.txt");
        FtpUtil.startDownDir(f, "E:/data1/",  "/data1/");

   }  
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章