- ftp_client_conf.properties
- host=192.168.72.51
- port=21
- userName=hundsun
- password=hundsun
- controlChannelKeepAlive=300
- fileRootDir=d:\\uploadfiles
- developModel=true
- PMSFTPClient.java
- /**
- * Copyright (c) 2011, WWW.HUNDSUN.COM All Rights Reserved.
- */
- package com.hundsun.pms.support;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.io.UnsupportedEncodingException;
- import java.net.SocketException;
- import java.util.Properties;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.apache.commons.net.PrintCommandListener;
- 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;
- import com.hundsun.jres.interfaces.exception.biz.JRESBizRuntimeException;
- import com.ibatis.common.resources.Resources;
- /**
- * 標題:PMSFtpClient.java<br>
- * 功能說明:<br>
- * 系統版本:v1.0<br>
- * 開發人員:[email protected]<br>
- * 開發時間:2012-4-9<br>
- * 功能描述:FTP客戶端<br>
- */
- public class PMSFTPClient {
- private static final Log log = LogFactory.getLog(PMSFTPClient.class);
- private static final String PATH = "/ftp_client_conf.properties";
- private static final String HOST = "host";
- private static final String PORT = "port";
- private static final String USER_NAME = "userName";
- private static final String PASSWORD = "password";
- private static final String SEPARATOR = File.separator;
- private static final String CONTROL_CHANNEL_KEEY_ALIVE = "controlChannelKeepAlive";
- private static final String DEVELOP_MODEL = "developModel";
- private static Properties clientConfig;
- private FTPClient client;
- public static void main(String[] args) throws Exception {
- // String local = "c:\\script.txt";
- // String remote = "\\uploadfiles\\template\\script.txt";
- // InputStream in = new FileInputStream(local);
- // PMSFTPClient ftpClient = new PMSFTPClient();
- // ftpClient.upload(local, remote, in);
- // ftpClient.download(remote, System.out);
- // ftpClient.deleteFile(remote);
- PMSFTPClient a = new PMSFTPClient();
- String path = "/home/pms";
- File f2 = new File("E:/pub/email/《夢幻西遊》用戶手冊.doc");
- OutputStream out = new FileOutputStream(f2);
- String filename2 = f2.getName();
- System.out.println(filename2);
- // a.downFile("172.19.10.105", 21, "pms", "hundsun",
- // "pub/email/《夢幻西遊》用戶手冊.doc", out);
- }
- public PMSFTPClient() {
- client = new FTPClient();
- if (clientConfig == null)
- clientConfig = new Properties();
- // 初始化配置信息
- initClientConfig();
- if (clientConfig.getProperty(DEVELOP_MODEL).trim().equals("true")) {
- // 設置將過程中使用到的命令輸出到控制檯
- client.addProtocolCommandListener(new PrintCommandListener(
- new PrintWriter(System.out)));
- }
- client.setControlKeepAliveTimeout(Long.parseLong(clientConfig
- .getProperty(CONTROL_CHANNEL_KEEY_ALIVE).trim()));
- // 連接FTP服務器
- connect();
- }
- private String toIso8859(String s) {
- try {
- s = new String(s.getBytes("UTF-8"), "iso8859_1");
- } catch (UnsupportedEncodingException e) {
- throw new JRESBizRuntimeException("-1", e.getMessage());
- }
- return s;
- }
- /**
- *
- * upload:上傳文件
- *
- * @param local
- * 本地要上傳的文件的絕對路徑
- * @param remote
- * 服務器上文件存放的相對路徑
- * @param is
- * 文件流
- * @return
- * @throws
- * @since PMSFTPClient.java Ver 1.0
- *
- * @author weinh 20111029 這裏做一個說明註釋了remote = toIso8859(remote);
- * 把編碼格式變爲GBK,然後remoteFileName = new
- * String(remoteFileName.getBytes("GBK"),"ISO-8859-1");
- * 以上調整解決了上傳中文名文件問題
- *
- *
- */
- public boolean upload(String local, String remote, InputStream is) {
- // remote = toIso8859(remote);
- remote = remote.replaceAll("//", "/");
- // 設置PassiveMode傳輸
- client.enterLocalPassiveMode();
- client.setControlEncoding("GBK");
- // 設置以二進制流的方式傳輸
- try {
- client.setFileType(FTP.BINARY_FILE_TYPE);
- // 對遠程目錄的處理
- String remoteFileName = remote;
- if (remote.contains(SEPARATOR)) {
- int index = remote.lastIndexOf(SEPARATOR) + 1;
- remoteFileName = remote.substring(index);
- String directory = remote.substring(0, index);
- if (!directory.equalsIgnoreCase(SEPARATOR)
- && !client.changeWorkingDirectory(directory)) {
- // 如果遠程目錄不存在,則遞歸創建遠程服務器目錄
- int start = 0;
- int end = 0;
- if (directory.startsWith(SEPARATOR)) {
- start = 1;
- } else {
- start = 0;
- }
- end = directory.indexOf(SEPARATOR, start);
- while (true) {
- String subDirectory = remote.substring(start, end);
- if (!client.changeWorkingDirectory(subDirectory)) {
- if (client.makeDirectory(subDirectory)) {
- client.changeWorkingDirectory(subDirectory);
- } else {
- log.error("創建目錄失敗");
- return false;
- }
- }
- start = end + 1;
- end = directory.indexOf(SEPARATOR, start);
- // 檢查所有目錄是否創建完畢
- if (end <= start) {
- break;
- }
- }
- }
- }
- // 檢查遠程是否存在文件
- FTPFile[] files = client.listFiles(remoteFileName);
- if (files.length == 1) {
- File f = new File(local);
- if (files[0].getName().equals(f.getName())) {
- // 刪除服務器上文件,重新上傳
- boolean deleted = client.deleteFile(remote);
- if (!deleted) {
- log.error("無法刪除已經上傳過的同名文件!");
- return false;
- }
- }
- // 嘗試移動文件內讀取指針,實現斷點續傳
- /*
- * if (is.skip(remoteSize) == remoteSize) {
- * client.setRestartOffset(remoteSize); if
- * (client.storeFile(remote, is)) { log.info("斷點續傳成功!"); return
- * true; } }
- */
- }
- remoteFileName = new String(remoteFileName.getBytes("GBK"),
- "ISO-8859-1");
- if (client.storeFile(remoteFileName, is)) {
- log.info("上傳成功!");
- return true;
- } else {
- log.error("上傳失敗!");
- return false;
- }
- } catch (IOException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", e.getMessage());
- } finally {
- try {
- is.close();
- } catch (IOException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", e.getMessage());
- }
- }
- }
- /**
- *
- * download:下載文件
- *
- * @param remote
- * 文件相對路徑
- * @param out
- * @return
- * @throws
- * @since PMSFTPClient.java Ver 1.0
- */
- public boolean download(String remote, OutputStream out) {
- // remote = toIso8859(remote);
- boolean result = true;
- client.enterLocalPassiveMode();
- client.setControlEncoding("GBK");
- try {
- client.setFileType(FTP.BINARY_FILE_TYPE);
- remote = new String(remote.getBytes("GBK"), "ISO-8859-1");
- result = client.retrieveFile(remote, out);
- } catch (IOException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", e.getMessage());
- } finally {
- try {
- out.flush();
- out.close();
- } catch (IOException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", e.getMessage());
- }
- }
- return result;
- }
- public FTPFile[] getFiles(String remote, OutputStream out) {
- remote = toIso8859(remote);
- client.enterLocalPassiveMode();
- client.setControlEncoding("UTF-8");
- try {
- client.setFileType(FTP.BINARY_FILE_TYPE);
- return client.listFiles();
- } catch (IOException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", e.getMessage());
- } finally {
- try {
- out.close();
- } catch (IOException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", e.getMessage());
- }
- }
- }
- /**
- *
- * deleteFile:刪除文件
- *
- * @param remote
- * 要刪除的文件路徑
- * @return
- * @throws
- * @since PMSFTPClient.java Ver 1.0
- */
- public boolean deleteFile(String remote) {
- try {
- remote = toIso8859(remote);
- boolean t = client.deleteFile(remote);
- if (t) {
- log.info(remote + " 刪除成功!");
- } else {
- log.info(remote + " 刪除失敗");
- }
- return t;
- } catch (IOException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", e.getMessage());
- }
- }
- private boolean connect() {
- int port = 0;
- try {
- port = Integer.valueOf(clientConfig.getProperty(PORT).trim());
- client.connect(clientConfig.getProperty(HOST).trim(), port);
- if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
- boolean b = client.login(clientConfig.getProperty(USER_NAME)
- .trim(), clientConfig.getProperty(PASSWORD).trim());
- if (b) {
- log.info("賬戶:" + clientConfig.getProperty(USER_NAME).trim()
- + " 成功連接到FTP服務器!");
- return true;
- }
- return false;
- }
- disconnect();
- return false;
- } catch (NumberFormatException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", "端口" + port + "連接失敗,原因是:"
- + e.getMessage());
- } catch (SocketException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", "與ftp 服務器通信失敗,原因是:"
- + e.getMessage());
- } catch (IOException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", e.getMessage());
- }
- }
- private void disconnect() {
- if (client.isConnected()) {
- try {
- client.disconnect();
- } catch (IOException e) {
- log.error(e.getMessage());
- throw new JRESBizRuntimeException("-1", e.getMessage());
- }
- }
- }
- private void initClientConfig() {
- InputStream in = null;
- try {
- in = Resources.getResourceAsStream(PATH);
- clientConfig.load(in);
- // in = new
- // FileInputStream("D:\\workspace\\PMS\\src\\ftp_client_conf.properties");
- } catch (IOException e1) {
- log.error(e1.getMessage());
- throw new JRESBizRuntimeException("-1",
- "讀取配置文件ftp_client_conf.properties失敗,原因是:" + e1.getMessage());
- }
- }
- /*
- * public boolean downFile(String ip, int port, String username, String
- * password, String fileName, OutputStream outputStream) { boolean success =
- * false; FTPClient ftp = new FTPClient(); try { ftp.connect(ip, port); //
- * 下面三行代碼必須要,而且不能改變編碼格式 ftp.setControlEncoding("GBK"); //
- * 如果採用默認端口,可以使用ftp.connect(url) 的方式直接連接FTP服務器 ftp.login(username,
- * password);// 登錄 ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
- * System.out.println("登陸成功。。。。"); download(ftp, fileName, outputStream); //
- * System.out.println(fileName); // fileName = new
- * String(fileName.getBytes("GBK"), "ISO-8859-1"); //
- * ftp.retrieveFile(fileName, outputStream); //
- * System.out.println(fileName); // outputStream.flush(); //
- * outputStream.close(); ftp.logout(); success = true; } catch (IOException
- * e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try {
- * ftp.disconnect(); } catch (IOException ioe) { } } } return success; }
- */
- }