亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java實現(xiàn)FTP文件與文件夾的上傳和下載

 更新時間:2016年12月23日 08:57:03   作者:一個弱者想變強  
本文主要分享了Java實現(xiàn)文件上傳和下載的具體實例,分為單個文件的上傳與下載和整個文件夾的上傳與下載。具有很好的參考價值,需要的朋友一起來看下吧

FTP 是File Transfer Protocol(文件傳輸協(xié)議)的英文簡稱,而中文簡稱為“文傳協(xié)議”。用于Internet上的控制文件的雙向傳輸。同時,它也是一個應用程序(Application)?;诓煌牟僮飨到y(tǒng)有不同的FTP應用程序,而所有這些應用程序都遵守同一種協(xié)議以傳輸文件。在FTP的使用當中,用戶經(jīng)常遇到兩個概念:"下載"(Download)和"上傳"(Upload)。"下載"文件就是從遠程主機拷貝文件至自己的計算機上;"上傳"文件就是將文件從自己的計算機中拷貝至遠程主機上。用Internet語言來說,用戶可通過客戶機程序向(從)遠程主機上傳(下載)文件。

首先下載了Serv-U將自己的電腦設置為了FTP文件服務器,方便操作。下面代碼的使用都是在FTP服務器已經(jīng)創(chuàng)建,并且要在代碼中寫好FTP連接的相關數(shù)據(jù)才可以完成。

1.FTP文件的上傳與下載(注意是單個文件的上傳與下載)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
 * 實現(xiàn)FTP文件上傳和文件下載
 */
public class FtpApche {
 private static FTPClient ftpClient = new FTPClient();
 private static String encoding = System.getProperty("file.encoding");
 /**
  * Description: 向FTP服務器上傳文件
  * 
  * @Version1.0
  * @param url
  *   FTP服務器hostname
  * @param port
  *   FTP服務器端口
  * @param username
  *   FTP登錄賬號
  * @param password
  *   FTP登錄密碼
  * @param path
  *   FTP服務器保存目錄,如果是根目錄則為“/”
  * @param filename
  *   上傳到FTP服務器上的文件名
  * @param input
  *   本地文件輸入流
  * @return 成功返回true,否則返回false
  */
 public static boolean uploadFile(String url, int port, String username,
   String password, String path, String filename, InputStream input) {
  boolean result = false;
  try {
   int reply;
   // 如果采用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
   ftpClient.connect(url);
   // ftp.connect(url, port);// 連接FTP服務器
   // 登錄
   ftpClient.login(username, password);
   ftpClient.setControlEncoding(encoding);
   // 檢驗是否連接成功
   reply = ftpClient.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
    System.out.println("連接失敗");
    ftpClient.disconnect();
    return result;
   }
   // 轉(zhuǎn)移工作目錄至指定目錄下
   boolean change = ftpClient.changeWorkingDirectory(path);
   ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
   if (change) {
    result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input);
    if (result) {
     System.out.println("上傳成功!");
    }
   }
   input.close();
   ftpClient.logout();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (ftpClient.isConnected()) {
    try {
     ftpClient.disconnect();
    } catch (IOException ioe) {
    }
   }
  }
  return result;
 }
 /**
  * 將本地文件上傳到FTP服務器上
  * 
  */
 public void testUpLoadFromDisk() {
  try {
   FileInputStream in = new FileInputStream(new File("D:/test02/list.txt"));
   boolean flag = uploadFile("10.0.0.102", 21, "admin","123456", "/", "lis.txt", in);
   System.out.println(flag);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }
 /**
  * Description: 從FTP服務器下載文件
  * 
  * @Version1.0
  * @param url
  *   FTP服務器hostname
  * @param port
  *   FTP服務器端口
  * @param username
  *   FTP登錄賬號
  * @param password
  *   FTP登錄密碼
  * @param remotePath
  *   FTP服務器上的相對路徑
  * @param fileName
  *   要下載的文件名
  * @param localPath
  *   下載后保存到本地的路徑
  * @return
  */
 public static boolean downFile(String url, int port, String username,
   String password, String remotePath, String fileName,
   String localPath) {
  boolean result = false;
  try {
   int reply;
   ftpClient.setControlEncoding(encoding);
   /*
    * 為了上傳和下載中文文件,有些地方建議使用以下兩句代替
    * new String(remotePath.getBytes(encoding),"iso-8859-1")轉(zhuǎn)碼。
    * 經(jīng)過測試,通不過。
    */
//   FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
//   conf.setServerLanguageCode("zh");
   ftpClient.connect(url, port);
   // 如果采用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
   ftpClient.login(username, password);// 登錄
   // 設置文件傳輸類型為二進制
   ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
   // 獲取ftp登錄應答代碼
   reply = ftpClient.getReplyCode();
   // 驗證是否登陸成功
   if (!FTPReply.isPositiveCompletion(reply)) {
    ftpClient.disconnect();
    System.err.println("FTP server refused connection.");
    return result;
   }
   // 轉(zhuǎn)移到FTP服務器目錄至指定的目錄下
   ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
   // 獲取文件列表
   FTPFile[] fs = ftpClient.listFiles();
   for (FTPFile ff : fs) {
    if (ff.getName().equals(fileName)) {
     File localFile = new File(localPath + "/" + ff.getName());
     OutputStream is = new FileOutputStream(localFile);
     ftpClient.retrieveFile(ff.getName(), is);
     is.close();
    }
   }
   ftpClient.logout();
   result = true;
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (ftpClient.isConnected()) {
    try {
     ftpClient.disconnect();
    } catch (IOException ioe) {
    }
   }
  }
  return result;
 }
 /**
  * 將FTP服務器上文件下載到本地
  * 
  */
 public void testDownFile() {
  try {
   boolean flag = downFile("10.0.0.102", 21, "admin",
     "123456", "/", "ip.txt", "E:/");
   System.out.println(flag);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 public static void main(String[] args) {
  FtpApche fa = new FtpApche();
  fa.testDownFile();
  fa.testUpLoadFromDisk();
 }
}

2.FTP文件夾的上傳與下載(注意是整個文件夾)

package ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
public class FTPTest_04 {
 private FTPClient ftpClient;
 private String strIp;
 private int intPort;
 private String user;
 private String password;
 private static Logger logger = Logger.getLogger(FTPTest_04.class.getName());
 /* * 
  * Ftp構造函數(shù) 
  */ 
 public FTPTest_04(String strIp, int intPort, String user, String Password) {
  this.strIp = strIp;
  this.intPort = intPort;
  this.user = user;
  this.password = Password;
  this.ftpClient = new FTPClient();
 }
 /** 
  * @return 判斷是否登入成功 
  * */ 
 public boolean ftpLogin() {
  boolean isLogin = false;
  FTPClientConfig ftpClientConfig = new FTPClientConfig();
  ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
  this.ftpClient.setControlEncoding("GBK");
  this.ftpClient.configure(ftpClientConfig);
  try {
   if (this.intPort > 0) {
    this.ftpClient.connect(this.strIp, this.intPort);
   }else {
    this.ftpClient.connect(this.strIp);
   }
   // FTP服務器連接回答 
   int reply = this.ftpClient.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
    this.ftpClient.disconnect();
    logger.error("登錄FTP服務失?。?);
    return isLogin;
   }
   this.ftpClient.login(this.user, this.password);
   // 設置傳輸協(xié)議 
   this.ftpClient.enterLocalPassiveMode();
   this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
   logger.info("恭喜" + this.user + "成功登陸FTP服務器");
   isLogin = true;
  }catch (Exception e) {
   e.printStackTrace();
   logger.error(this.user + "登錄FTP服務失?。? + e.getMessage());
  }
  this.ftpClient.setBufferSize(1024 * 2);
  this.ftpClient.setDataTimeout(30 * 1000);
  return isLogin;
 }
 /** 
  * @退出關閉服務器鏈接 
  * */ 
 public void ftpLogOut() {
  if (null != this.ftpClient && this.ftpClient.isConnected()) {
   try {
    boolean reuslt = this.ftpClient.logout();// 退出FTP服務器 
    if (reuslt) {
     logger.info("成功退出服務器");
    }
   }catch (IOException e) {
    e.printStackTrace();
    logger.warn("退出FTP服務器異常!" + e.getMessage());
   }finally {
    try {
     this.ftpClient.disconnect();// 關閉FTP服務器的連接 
    }catch (IOException e) {
     e.printStackTrace();
     logger.warn("關閉FTP服務器的連接異常!");
    }
   }
  }
 }
 /*** 
  * 上傳Ftp文件 
  * @param localFile 當?shù)匚募?
  * @param romotUpLoadePath上傳服務器路徑 - 應該以/結束 
  * */ 
 public boolean uploadFile(File localFile, String romotUpLoadePath) {
  BufferedInputStream inStream = null;
  boolean success = false;
  try {
   this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改變工作路徑 
   inStream = new BufferedInputStream(new FileInputStream(localFile));
   logger.info(localFile.getName() + "開始上傳.....");
   success = this.ftpClient.storeFile(localFile.getName(), inStream);
   if (success == true) {
    logger.info(localFile.getName() + "上傳成功");
    return success;
   }
  }catch (FileNotFoundException e) {
   e.printStackTrace();
   logger.error(localFile + "未找到");
  }catch (IOException e) {
   e.printStackTrace();
  }finally {
   if (inStream != null) {
    try {
     inStream.close();
    }catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return success;
 }
 /*** 
  * 下載文件 
  * @param remoteFileName 待下載文件名稱 
  * @param localDires 下載到當?shù)啬莻€路徑下 
  * @param remoteDownLoadPath remoteFileName所在的路徑 
  * */ 
 public boolean downloadFile(String remoteFileName, String localDires, 
   String remoteDownLoadPath) {
  String strFilePath = localDires + remoteFileName;
  BufferedOutputStream outStream = null;
  boolean success = false;
  try {
   this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
   outStream = new BufferedOutputStream(new FileOutputStream( 
     strFilePath));
   logger.info(remoteFileName + "開始下載....");
   success = this.ftpClient.retrieveFile(remoteFileName, outStream);
   if (success == true) {
    logger.info(remoteFileName + "成功下載到" + strFilePath);
    return success;
   }
  }catch (Exception e) {
   e.printStackTrace();
   logger.error(remoteFileName + "下載失敗");
  }finally {
   if (null != outStream) {
    try {
     outStream.flush();
     outStream.close();
    }catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  if (success == false) {
   logger.error(remoteFileName + "下載失敗!!!");
  }
  return success;
 }
 /*** 
  * @上傳文件夾 
  * @param localDirectory 
  *   當?shù)匚募A 
  * @param remoteDirectoryPath 
  *   Ftp 服務器路徑 以目錄"/"結束 
  * */ 
 public boolean uploadDirectory(String localDirectory, 
   String remoteDirectoryPath) {
  File src = new File(localDirectory);
  try {
   remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
   boolean makeDirFlag = this.ftpClient.makeDirectory(remoteDirectoryPath);
   System.out.println("localDirectory : " + localDirectory);
   System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
   System.out.println("src.getName() : " + src.getName());
   System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
   System.out.println("makeDirFlag : " + makeDirFlag);
   // ftpClient.listDirectories();
  }catch (IOException e) {
   e.printStackTrace();
   logger.info(remoteDirectoryPath + "目錄創(chuàng)建失敗");
  }
  File[] allFile = src.listFiles();
  for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
   if (!allFile[currentFile].isDirectory()) {
    String srcName = allFile[currentFile].getPath().toString();
    uploadFile(new File(srcName), remoteDirectoryPath);
   }
  }
  for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
   if (allFile[currentFile].isDirectory()) {
    // 遞歸 
    uploadDirectory(allFile[currentFile].getPath().toString(), 
      remoteDirectoryPath);
   }
  }
  return true;
 }
 /*** 
  * @下載文件夾 
  * @param localDirectoryPath本地地址 
  * @param remoteDirectory 遠程文件夾 
  * */ 
 public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
  try {
   String fileName = new File(remoteDirectory).getName();
   localDirectoryPath = localDirectoryPath + fileName + "http://";
   new File(localDirectoryPath).mkdirs();
   FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
   for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
    if (!allFile[currentFile].isDirectory()) {
     downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);
    }
   }
   for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
    if (allFile[currentFile].isDirectory()) {
     String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
     downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
    }
   }
  }catch (IOException e) {
   e.printStackTrace();
   logger.info("下載文件夾失敗");
   return false;
  }
  return true;
 }
 // FtpClient的Set 和 Get 函數(shù) 
 public FTPClient getFtpClient() {
  return ftpClient;
 }
 public void setFtpClient(FTPClient ftpClient) {
  this.ftpClient = ftpClient;
 }
 public static void main(String[] args) throws IOException {
  FTPTest_04 ftp=new FTPTest_04("10.0.0.102",21,"admin","123456");
  ftp.ftpLogin();
  System.out.println("1");
  //上傳文件夾 
  boolean uploadFlag = ftp.uploadDirectory("D:\\test02", "/"); //如果是admin/那么傳的就是所有文件,如果只是/那么就是傳文件夾
  System.out.println("uploadFlag : " + uploadFlag);
  //下載文件夾 
  ftp.downLoadDirectory("d:\\tm", "/");
  ftp.ftpLogOut();
 }
}

以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!

相關文章

  • java使用BeanUtils.copyProperties踩坑經(jīng)歷

    java使用BeanUtils.copyProperties踩坑經(jīng)歷

    最近在做個項目,踩了個坑特此記錄一下,本文主要介紹了使用BeanUtils.copyProperties踩坑經(jīng)歷,需要的朋友們下面隨著小編來一起學習學習吧
    2021-05-05
  • Java中5種異步實現(xiàn)的方式詳解

    Java中5種異步實現(xiàn)的方式詳解

    同步操作如果遇到一個耗時的方法,需要阻塞等待,那么我們有沒有辦法解決呢?讓它異步執(zhí)行,下面我會詳解異步及實現(xiàn),需要的可以參考一下
    2022-09-09
  • spring解決循環(huán)依賴的簡單方法

    spring解決循環(huán)依賴的簡單方法

    這篇文章主要給大家介紹了關于spring解決循環(huán)依賴的簡單方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-09-09
  • java中設計模式之適配器模式

    java中設計模式之適配器模式

    這篇文章主要介紹了java中設計模式之適配器模式的相關資料,適配器模式將一個類的接口轉(zhuǎn)換成客戶期望的另一個接口。適配器讓原本不兼容的類可以合作得親密無間,需要的朋友可以參考下
    2017-09-09
  • 基于Spring Boot不同的環(huán)境使用不同的配置方法

    基于Spring Boot不同的環(huán)境使用不同的配置方法

    下面小編就為大家分享一篇基于Spring Boot不同的環(huán)境使用不同的配置方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01
  • 值得收藏的2017年Java開發(fā)崗位面試題

    值得收藏的2017年Java開發(fā)崗位面試題

    這篇文章主要為大家推薦一份值得收藏的2017年Java開發(fā)崗位面試題,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-08-08
  • mybatis項目兼容mybatis-plus問題

    mybatis項目兼容mybatis-plus問題

    這篇文章主要介紹了mybatis項目兼容mybatis-plus問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • SpringBoot?SPI?機制和實現(xiàn)自定義?starter

    SpringBoot?SPI?機制和實現(xiàn)自定義?starter

    這篇文章主要介紹了SpringBoot?SPI機制和實現(xiàn)自定義?starter,全稱是Service?Provider?Interface。簡單翻譯的話,就是服務提供者接口,是一種尋找服務實現(xiàn)的機制
    2022-08-08
  • java之抽象類和繼承抽象類解讀

    java之抽象類和繼承抽象類解讀

    這篇文章主要介紹了java之抽象類和繼承抽象類,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Spring-boot原理及spring-boot-starter實例和代碼

    Spring-boot原理及spring-boot-starter實例和代碼

    spring-boot的starter是一個通過maven完成自包含并通過annotation配置使得可被spring上下文發(fā)現(xiàn)并實例化的一個可插拔的組件或服務。這篇文章主要介紹了Spring-boot原理及spring-boot-starter實例和代碼 ,需要的朋友可以參考下
    2019-06-06

最新評論