java連接ftp,java連接ftp上傳文件

本文目錄一覽:

java如何測試連接ftp是否通

java測試連接ftp是否連通可以使用判斷是否有異常來決定,實例如下:

/** 

     * connectServer 

     * 連接ftp伺服器 

     * @throws java.io.IOException 

     * @param path 文件夾,空代表根目錄 

     * @param password 密碼 

     * @param user    登陸用戶 

     * @param server 伺服器地址 

     */ 

  public void connectServer(String server, String user, String password,  String path) 

  throws IOException 

   { 

     // server:FTP伺服器的IP地址;user:登錄FTP伺服器的用戶名 

     // password:登錄FTP伺服器的用戶名的口令;path:FTP伺服器上的路徑 

      ftpClient = new FtpClient(); 

      ftpClient.openServer(server); 

      ftpClient.login(user, password); 

     //path是ftp服務下主目錄的子目錄 

     if (path.length() != 0)   ftpClient.cd(path); 

     //用2進位上傳、下載 

      ftpClient.binary();      

/** 

     * upload 

     * 上傳文件 

     * @throws java.lang.Exception 

     * @return -1 文件不存在 

     *           -2 文件內容為空 

     *           0 成功上傳,返迴文件的大小 

     * @param newname 上傳後的新文件名 

     * @param filename 上傳的文件 

     */ 

public long upload(String filename,String newname) throws Exception 

     long result = 0; 

      TelnetOutputStream os = null; 

      FileInputStream is = null; 

     try {          

          java.io.File file_in = new java.io.File(filename); 

         if (!file_in.exists()) return -1; 

         if (file_in.length()==0) return -2; 

          os = ftpClient.put(newname); 

          result = file_in.length(); 

          is = new FileInputStream(file_in); 

         byte[] bytes = new byte[1024]; 

         int c; 

         while ((c = is.read(bytes)) != -1) { 

               os.write(bytes, 0, c); 

          } 

      } finally { 

         if (is != null) { 

              is.close(); 

          } 

         if (os != null) { 

             os.close(); 

          } 

      } 

    return result; 

/** 

     * upload 

     * @throws java.lang.Exception 

     * @return 

     * @param filename 

     */ 

public long upload(String filename) 

throws Exception 

    String newname = “”; 

    if (filename.indexOf(“/”)-1) 

     { 

        newname = filename.substring(filename.lastIndexOf(“/”)+1); 

     }else 

     { 

        newname = filename; 

     } 

    return upload(filename,newname); 

/** 

     *   download 

     *   從ftp下載文件到本地 

     * @throws java.lang.Exception 

     * @return 

     * @param newfilename 本地生成的文件名 

     * @param filename 伺服器上的文件名 

     */ 

public long download(String filename,String newfilename) 

throws Exception 

{   

    long result = 0; 

     TelnetInputStream is = null; 

     FileOutputStream os = null; 

    try 

     { 

        is = ftpClient.get(filename);        

        java.io.File outfile = new java.io.File(newfilename); 

        os = new FileOutputStream(outfile); 

       byte[] bytes = new byte[1024]; 

       int c; 

       while ((c = is.read(bytes)) != -1) { 

            os.write(bytes, 0, c); 

            result = result + c; 

        } 

     } catch (IOException e) 

     { 

        e.printStackTrace(); 

     } 

    finally { 

         if (is != null) { 

              is.close(); 

          } 

         if (os != null) { 

             os.close(); 

          } 

      } 

     return result; 

/** 

   * 取得某個目錄下的所有文件列表 

   * 

   */ 

public List getFileList(String path) 

     List list = new ArrayList(); 

    try 

     { 

        DataInputStream dis = new   DataInputStream(ftpClient.nameList(path)); 

       String filename = “”; 

       while((filename=dis.readLine())!=null)   

        {   

          list.add(filename);         

        }   

    

     } catch (Exception e) 

     { 

        e.printStackTrace(); 

     } 

    return list; 

/** 

     * closeServer 

     * 斷開與ftp伺服器的鏈接 

     * @throws java.io.IOException 

     */ 

public void closeServer() 

throws IOException 

{    

   try 

    { 

      if (ftpClient != null) 

       { 

         ftpClient.closeServer();      

       } 

    } catch (IOException e) { 

       e.printStackTrace(); 

    } 

   

  public static void main(String [] args) throws Exception 

   { 

     FtpUtil ftp = new FtpUtil(); 

    try { 

         //連接ftp伺服器 

          (“10.163.7.15”, “cxl”, “1”, “info2”); 

         /**   上傳文件到 info2 文件夾下 */ 

          System.out.println(“filesize:”+(“f:/download/Install.exe”)+”位元組”); 

         /** 取得info2文件夾下的所有文件列表,並下載到 E盤下 */ 

          List list = (“.”); 

         for (int i=0;ilist.size();i++) 

          { 

            String filename = (String)list.get(i); 

             System.out.println(filename); 

             (filename,”E:/”+filename); 

          } 

     } catch (Exception e) { 

       /// 

     }finally 

     { 

        ; 

     } 

   }   

}

java連接ftp是主動模式還是被動模式

正常情況下,默認使用主動模式 連接ftp;如果ftp仍然是登陸成功但是沒有上傳或下載文件,就在登陸後加入一行代碼,客戶端使用被動方式連接ftp服務端

ftpC.login(user, password);

// ftpC.enterLocalPassiveMode();

if (null != remotePath) {

// 打開進入指定目錄

ftpC.changeWorkingDirectory(remotePath);

}

JAVA編寫FTP連接報錯java.net.ConnectException: Connection refused: connect FTP

你用的FTPClient引入不對吧,我們項目上都是用的

import org.apache.commons.net.;

import org.apache.commons.net.;

import org.apache.commons.net.;

下面是我們項目上用到的FTP的實現代碼(FTP需要先連接,再登錄,之後就是校驗登錄是否成功),具體代碼如下:

/**

  * 獲取FTPClient對象

  *

  * @param ftpHost FTP主機伺服器

  * @param ftpPassword FTP 登錄密碼

  * @param ftpUserName FTP登錄用戶名

  * @param ftpPort FTP埠 默認為21

  * @return FTPClient

  * @throws Exception

  */

 public static FTPClient getFTPClient(String ftpHost, String ftpUserName,

   String ftpPassword, int ftpPort) throws Exception {

  try {

   FTPClient ftpClient = new FTPClient();

   ftpClient.connect(ftpHost, ftpPort);// 連接FTP伺服器

   ftpClient.login(ftpUserName, ftpPassword);// 登陸FTP伺服器

   if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {

    logger.error(“未連接到FTP,用戶名或密碼錯誤!”);

    ftpClient.disconnect();

    return null;

   } else {

    logger.info(“FTP連接成功!”);

    return ftpClient;

   }

  } catch (SocketException socketException) {

   logger.error(“FTP的IP地址可能錯誤,請正確配置!”);

   throw socketException;

  } catch (IOException ioException) {

   logger.error(“FTP的埠錯誤,請正確配置!”);

   throw ioException;

  }

 }

如何用java連接到ftp上

現在已經封裝好了的方法,不需要任何其他知識即可連接的。只需要知道ftp登錄用戶名、密碼、埠、存儲路徑即可。

package zn.ccfccb.util;

import hkrt.b2b.view.util.Log;

import hkrt.b2b.view.util.ViewUtil;

import java.io.ByteArrayOutputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import org.apache.commons.net.;

import org.apache.commons.net.;

public class CCFCCBFTP {

/**

* 上傳文件

*

* @param fileName

* @param plainFilePath 明文文件路徑路徑

* @param filepath

* @return

* @throws Exception

*/

public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {

FileInputStream fis = null;

ByteArrayOutputStream bos = null;

FTPClient ftpClient = new FTPClient();

String bl = “false”;

try {

fis = new FileInputStream(plainFilePath);

bos = new ByteArrayOutputStream(fis.available());

byte[] buffer = new byte[1024];

int count = 0;

while ((count = fis.read(buffer)) != -1) {

bos.write(buffer, 0, count);

}

bos.flush();

Log.info(“加密上傳文件開始”);

Log.info(“連接遠程上傳伺服器”+CCFCCBUtil.CCFCCBHOSTNAME+”:”+22);

ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);

ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);

// Log.info(“連接遠程上傳伺服器”+”192.168.54.106:”+2021);

// ftpClient.connect(“192.168.54.106”, 2021);

// ftpClient.login(“hkrt-CCFCCBHK”, “3OLJheziiKnkVcu7Sigz”);

FTPFile[] fs;

fs = ftpClient.listFiles();

for (FTPFile ff : fs) {

if (ff.getName().equals(filepath)) {

bl=”true”;

ftpClient.changeWorkingDirectory(“/”+filepath+””);

}

}

Log.info(“檢查文件路徑是否存在:/”+filepath);

if(“false”.equals(bl)){

ViewUtil.dataSEErrorPerformedCommon( “查詢文件路徑不存在:”+”/”+filepath);

return bl;

}

ftpClient.setBufferSize(1024);

ftpClient.setControlEncoding(“GBK”);

// 設置文件類型(二進位)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

ftpClient.storeFile(fileName, fis);

Log.info(“上傳文件成功:”+fileName+”。文件保存路徑:”+”/”+filepath+”/”);

return bl;

} catch (Exception e) {

throw e;

} finally {

if (fis != null) {

try {

fis.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

if (bos != null) {

try {

bos.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

}

}

/**

*下載並解壓文件

*

* @param localFilePath

* @param fileName

* @param routeFilepath

* @return

* @throws Exception

*/

public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {

FileInputStream fis = null;

ByteArrayOutputStream bos = null;

FileOutputStream fos = null;

FTPClient ftpClient = new FTPClient();

String SFP = System.getProperty(“file.separator”);

String bl = “false”;

try {

Log.info(“下載並解密文件開始”);

Log.info(“連接遠程下載伺服器”+CCFCCBUtil.CCFCCBHOSTNAME+”:”+22);

ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);

ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);

// ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);

// ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);

FTPFile[] fs;

ftpClient.makeDirectory(routeFilepath);

ftpClient.changeWorkingDirectory(routeFilepath);

bl = “false”;

fs = ftpClient.listFiles();

for (FTPFile ff : fs) {

if (ff.getName().equals(fileName)) {

bl = “true”;

Log.info(“下載文件開始。”);

ftpClient.setBufferSize(1024);

// 設置文件類型(二進位)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

InputStream is = ftpClient.retrieveFileStream(fileName);

bos = new ByteArrayOutputStream(is.available());

byte[] buffer = new byte[1024];

int count = 0;

while ((count = is.read(buffer)) != -1) {

bos.write(buffer, 0, count);

}

bos.flush();

fos = new FileOutputStream(localFilePath+SFP+fileName);

fos.write(bos.toByteArray());

Log.info(“下載文件結束:”+localFilePath);

}

}

Log.info(“檢查文件是否存:”+fileName+” “+bl);

if(“false”.equals(bl)){

ViewUtil.dataSEErrorPerformedCommon(“查詢無結果,請稍後再查詢。”);

return bl;

}

return bl;

} catch (Exception e) {

throw e;

} finally {

if (fis != null) {

try {

fis.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

if (bos != null) {

try {

bos.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

if (fos != null) {

try {

fos.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

原創文章,作者:PCLG,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/141778.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
PCLG的頭像PCLG
上一篇 2024-10-08 18:05
下一篇 2024-10-08 18:05

相關推薦

  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • java client.getacsresponse 編譯報錯解決方法

    java client.getacsresponse 編譯報錯是Java編程過程中常見的錯誤,常見的原因是代碼的語法錯誤、類庫依賴問題和編譯環境的配置問題。下面將從多個方面進行分析…

    編程 2025-04-29
  • Java Bean載入過程

    Java Bean載入過程涉及到類載入器、反射機制和Java虛擬機的執行過程。在本文中,將從這三個方面詳細闡述Java Bean載入的過程。 一、類載入器 類載入器是Java虛擬機…

    編程 2025-04-29
  • Java騰訊雲音視頻對接

    本文旨在從多個方面詳細闡述Java騰訊雲音視頻對接,提供完整的代碼示例。 一、騰訊雲音視頻介紹 騰訊雲音視頻服務(Cloud Tencent Real-Time Communica…

    編程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介紹

    本文將詳細介紹Java Milvus SearchParam withoutFields的相關知識和用法。 一、什麼是Java Milvus SearchParam without…

    編程 2025-04-29
  • Java 8中某一周的周一

    Java 8是Java語言中的一個版本,於2014年3月18日發布。本文將從多個方面對Java 8中某一周的周一進行詳細的闡述。 一、數組處理 Java 8新特性之一是Stream…

    編程 2025-04-29
  • Java判斷字元串是否存在多個

    本文將從以下幾個方面詳細闡述如何使用Java判斷一個字元串中是否存在多個指定字元: 一、字元串遍歷 字元串是Java編程中非常重要的一種數據類型。要判斷字元串中是否存在多個指定字元…

    編程 2025-04-29
  • VSCode為什麼無法運行Java

    解答:VSCode無法運行Java是因為默認情況下,VSCode並沒有集成Java運行環境,需要手動添加Java運行環境或安裝相關插件才能實現Java代碼的編寫、調試和運行。 一、…

    編程 2025-04-29
  • Java任務下發回滾系統的設計與實現

    本文將介紹一個Java任務下發回滾系統的設計與實現。該系統可以用於執行複雜的任務,包括可回滾的任務,及時恢復任務失敗前的狀態。系統使用Java語言進行開發,可以支持多種類型的任務。…

    編程 2025-04-29
  • Java 8 Group By 會影響排序嗎?

    是的,Java 8中的Group By會對排序產生影響。本文將從多個方面探討Group By對排序的影響。 一、Group By的概述 Group By是SQL中的一種常見操作,它…

    編程 2025-04-29

發表回復

登錄後才能評論