1. 程式人生 > 實用技巧 >Java使用FTPClient上傳下載檔案

Java使用FTPClient上傳下載檔案

package com.founder.mrp.util;

import com.founder.mrp.util.storage.StorageFile;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;


public class FtpUtil {

    
/** * 獲取FTPClient物件 * * @param ftpHost FTP主機伺服器 * @param ftpPassword FTP 登入密碼 * @param ftpUserName FTP登入使用者名稱 * @param ftpPort FTP埠 預設為21 * @return */ public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword,
int ftpPort) { FTPClient ftpClient = new FTPClient(); try { ftpClient = new FTPClient(); ftpClient.connect(ftpHost, ftpPort);// 連線FTP伺服器 ftpClient.login(ftpUserName, ftpPassword);// 登入FTP伺服器 if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { System.out.println(
"未連線到FTP,使用者名稱或密碼錯誤。"); ftpClient.disconnect(); } else { System.out.println("FTP連線成功。"); } } catch (SocketException e) { e.printStackTrace(); System.out.println("FTP的IP地址可能錯誤,請正確配置。"); } catch (IOException e) { e.printStackTrace(); System.out.println("FTP的埠錯誤,請正確配置。"); } return ftpClient; } /* * 從FTP伺服器下載檔案 * * @param ftpHost FTP IP地址 * @param ftpUserName FTP 使用者名稱 * @param ftpPassword FTP使用者名稱密碼 * @param ftpPort FTP埠 * @param ftpPath FTP伺服器中檔案所在路徑 格式: ftptest/aa * @param localPath 下載到本地的位置 格式:H:/download * @param fileName 檔名稱 */ public static void downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String localPath, String fileName) { FTPClient ftpClient = null; try { ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); ftpClient.setControlEncoding("UTF-8"); // 中文支援 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(ftpPath); File localFile = new File(localPath + File.separatorChar + fileName); OutputStream os = new FileOutputStream(localFile); ftpClient.retrieveFile(fileName, os); os.close(); ftpClient.logout(); } catch (FileNotFoundException e) { System.out.println("沒有找到" + ftpPath + "檔案"); e.printStackTrace(); } catch (SocketException e) { System.out.println("連線FTP失敗."); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.out.println("檔案讀取錯誤。"); e.printStackTrace(); } } /* * 從FTP伺服器下載檔案 * * @param ftpHost FTP IP地址 * @param ftpUserName FTP 使用者名稱 * @param ftpPassword FTP使用者名稱密碼 * @param ftpPort FTP埠 * @param ftpPath FTP伺服器中檔案所在路徑 格式: ftptest/aa * @param localPath 下載到本地的位置 格式:H:/download * @param fileName 檔名稱 */ public static void downloadFtpFileErp(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String fileName, StorageFile targetFile) { FTPClient ftpClient = null; try { ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); ftpClient.setControlEncoding("GBK"); // 中文支援 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes("GBK"), "ISO-8859-1")); targetFile.getParent().mkdirs(); try (OutputStream output = targetFile.getOutputStream(false); InputStream inStream = ftpClient.retrieveFileStream(new String(fileName.getBytes("GBK"), "ISO-8859-1"))) { byte[] buf = new byte[8192]; int n; while ((n = inStream.read(buf, 0, buf.length)) != -1) { output.write(buf, 0, n); } } } catch (FileNotFoundException e) { System.out.println("沒有找到" + ftpPath + "檔案"); e.printStackTrace(); } catch (SocketException e) { System.out.println("連線FTP失敗."); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.out.println("檔案讀取錯誤。"); e.printStackTrace(); } finally { if (ftpClient != null) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { try{ // downLoadPDFByUrl("http://nps.fltrp.com:805/wycode/30328b575cbc2dd64a4a0cd7d33244f3.pdf", // "ELISA.pdf",null); String ftpHost ="172.19.42.87"; String ftpUserName = "administrator"; String ftpPassword = "Founder123"; int ftpPort = 21; String ftpPath = "\\20551630-8A2D-B95C-F07E-4A4128B6B499\\Store File\\Normalized File"; String fileName = "2187.pdf"; String filePath = "/"; String localPath = "D:\\"; File file =new File("D:\\data.xml"); FileInputStream inStream=new FileInputStream(file); //上傳 uploadFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, fileName, inStream, filePath,0); //下載 downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName); }catch (Exception e) { // TODO: handle exception } // downloadFtpFileErp("172.19.45.56", "administrator", "Founder123!", 21, "F:/FTPtest", "", "新建文字文件"); // downloadFtpFile("172.19.45.56", "administrator", "Founder123!", 21, "F:/FTPtest", "F:/test", "新建文字文件.txt"); } /** * 從網路Url中下載檔案 * @param urlStr * @param fileName uuid * @param savePath 伺服器路徑 * @throws IOException */ public static void downLoadPDFByUrl(String urlStr,String fileName,StorageFile targetFile){ URL url=null; HttpURLConnection conn=null; try { url = new URL(urlStr); conn = (HttpURLConnection)url.openConnection(); //設定超時間為3秒 conn.setConnectTimeout(5*1000); //防止遮蔽程式抓取而返回403錯誤 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到輸入流 InputStream inputStream = conn.getInputStream(); //獲取自己陣列 byte[] getData = readInputStream(inputStream); //檔案儲存位置 /*File saveDir = new File(savePath); if(!saveDir.exists()){ saveDir.mkdir(); } File file = new File(saveDir+ File.separator+fileName); FileOutputStream fos = new FileOutputStream(file);*/ targetFile.getParent().mkdirs(); OutputStream fos = targetFile.getOutputStream(false); fos.write(getData); if(fos!=null){ fos.close(); } if(inputStream!=null){ inputStream.close(); } System.out.println("info:"+url+" download success"); } catch (FileNotFoundException e) { System.out.println("沒有找到檔案"); e.printStackTrace(); } catch (SocketException e) { System.out.println("網路連線失敗"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.out.println("檔案讀取錯誤。"); e.printStackTrace(); } finally { if (conn != null) { try { conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } } /** * 從輸入流中獲取位元組陣列 * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } /** * Description: 向FTP伺服器上傳檔案 * @param ftpHost FTP伺服器hostname * @param ftpUserName 賬號 * @param ftpPassword 密碼 * @param ftpPort 埠 * @param ftpPath FTP伺服器中檔案所在路徑 格式: ftptest/aa * @param fileName ftp檔名稱 * @param input 檔案流 * @return 成功返回true,否則返回false */ public static boolean uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String fileName,InputStream input,String filePath,long filesize) { boolean success = false; FTPClient ftpClient = null; String[] ftpPathDir=ftpPath.split("/");//ftp目錄 String[] dir=filePath.split("/");//建立多級目錄 try { int reply; ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); reply = ftpClient.getReplyCode(); for(int i=1;i<ftpPathDir.length;i++){ ftpClient.makeDirectory(new String(ftpPathDir[i].getBytes("GBK"),"iso-8859-1")); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); return success; } ftpClient.setControlEncoding("GBK"); // 中文支援 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); //取消伺服器獲取自身Ip地址和提交的host進行匹配 當不一致時會丟擲異常 ftpClient.setRemoteVerificationEnabled(false); ftpClient.changeWorkingDirectory(new String(ftpPathDir[i].getBytes("GBK"),"iso-8859-1")); } for(int i=0;i<dir.length;i++){ if(!dir[i].equals("")){ ftpClient.makeDirectory(new String(dir[i].getBytes("GBK"),"iso-8859-1")); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); return success; } ftpClient.setControlEncoding("GBK"); // 中文支援 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(new String(dir[i].getBytes("GBK"),"iso-8859-1")); } } //預設FTP上傳速度過慢,由於預設緩衝區大小1024位元組,將緩衝區大小改為10M ftpClient.setBufferSize(1024*1024*10); ftpClient.storeFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), input); input.close(); ftpClient.logout(); success = true; } catch (Exception e) { e.printStackTrace(); return success; } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { } } } return success; } }