在前面層用Apache Commons Net工具包實現了Java FTP單個文件的上傳下載功能,此次,實現的是對一個本地目錄的上傳,實現費了很大勁,雖然實現了 ,可是感受仍是對此封裝不是很是滿意,改用了其餘的FTP客戶端工具。將這個半成品放出來供各位研究吧。
package comftp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Properties;
/**
* Created by IntelliJ IDEA.
*
* @author leizhimin 2008-9-12 10:32:39
*/
public
class FtpTest {
public
static Log logger = LogFactory.getLog(FtpTest.
class);
private
static String userName;
//FTP 登陸用戶名
private
static String password;
//FTP 登陸密碼
private
static String ip;
//FTP 服務器地址IP地址
private
static
int port;
//FTP 端口
private
static Properties property =
null;
//屬性集
private
static String configFile =
"E:\\test\\comftp\\ftpconfig.properties";
//配置文件的路徑名
private
static FTPClient ftpClient =
null;
//FTP 客戶端代理
//時間格式化
private
static SimpleDateFormat dateFormat =
new SimpleDateFormat(
"yyyy-MM-dd hh:mm");
//FTP狀態碼
public
static
int i = 1;
public
static
void main(String[] args) {
connectServer();
setFileType(FTP.BINARY_FILE_TYPE);
// 設置傳輸二進制文件
uploadManyFile(
new File(
"C:\\ooo\\upx"),
new File(
"C:\\ooo\\upx"),
"/admin/ttt");
closeConnect();
// 關閉鏈接
}
/**
* 上傳單個文件,並重命名
*
* @param localFile--本地文件路徑
* @param distFolder--新的文件名,能夠命名爲空""
* @return true 上傳成功,false 上傳失敗
*/
public
static
boolean uploadFile(File localFile,
final File localRootFile,
final String distFolder) {
System.out.println(
" -------------------------");
boolean flag =
true;
try {
connectServer();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
InputStream input =
new FileInputStream(localFile);
// if (input == null) {
// System.out.println("本地文件"+localFile.getPath()+"不存在!");
// }
// if (newFileName.trim().equals("")) {
// newFileName = localFile.getName();
// }
String furi1 = localFile.getParentFile().getAbsoluteFile().toURI().toString();
String furi2 = localRootFile.getParentFile().getAbsoluteFile().toURI().toString();
String objFolder = distFolder + File.separator + furi1.substring(furi2.length());
ftpClient.changeWorkingDirectory(
"/");
ftpClient.makeDirectory(objFolder);
System.out.println(
"a>>>>>>> : " + distFolder + File.separator + localFile.getParent());
System.out.println(
"x>>>>>>> : " + objFolder);
ftpClient.changeWorkingDirectory(objFolder);
System.out.println(
"b>>>>>>> : " + localFile.getPath() +
" " + ftpClient.printWorkingDirectory());
flag = ftpClient.storeFile(localFile.getName(), input);
if (flag) {
System.out.println(
"上傳文件成功!");
}
else {
System.out.println(
"上傳文件失敗!");
}
input.close();
}
catch (IOException e) {
e.printStackTrace();
logger.debug(
"本地文件上傳失敗!", e);
}
catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 上傳多個文件
*
* @param localFile--本地文件夾路徑
* @return true 上傳成功,false 上傳失敗
*/
public
static String uploadManyFile(String localFile) {
boolean flag =
true;
StringBuffer strBuf =
new StringBuffer();
try {
connectServer();
File file =
new File(localFile);
// 在此目錄中找文件
File fileList[] = file.listFiles();
for (File f : fileList) {
if (f.isDirectory()) {
// 文件夾中還有文件夾
uploadManyFile(f.getAbsolutePath());
}
else {
}
if (!flag) {
strBuf.append(f.getName() +
"\r\n");
}
}
System.out.println(strBuf.toString());
}
catch (NullPointerException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
logger.debug(
"本地文件上傳失敗!", e);
}
return strBuf.toString();
}
/**
* 上傳多個文件
*
* @param localFile,--本地文件夾路徑
* @param distFolder--目標路徑
* @return true 上傳成功,false 上傳失敗
*/
public
static String uploadManyFile(File localFile,
final File localRootFile,
final String distFolder) {
System.out.println(
"-------------------------");
boolean flag =
true;
StringBuffer strBuf =
new StringBuffer();
int n = 0;
try {
connectServer();
ftpClient.makeDirectory(distFolder + File.separator + localFile.getParent());
File fileList[] = localFile.listFiles();
for (File upfile : fileList) {
if (upfile.isDirectory()) {
// 文件夾中還有文件夾
uploadManyFile(upfile, localRootFile, distFolder);
}
else {
flag = uploadFile(upfile, localRootFile, distFolder);
}
if (!flag) {
strBuf.append(upfile.getName() +
"\r\n");
}
}
System.out.println(strBuf.toString());
}
catch (NullPointerException e) {
e.printStackTrace();
logger.debug(
"本地文件上傳失敗!找不到上傳文件!", e);
}
catch (Exception e) {
e.printStackTrace();
logger.debug(
"本地文件上傳失敗!", e);
}
return strBuf.toString();
}
/**
* 下載文件
*
* @param remoteFileName --服務器上的文件名
* @param localFileName--本地文件名
* @return true 下載成功,false 下載失敗
*/
public
static
boolean loadFile(String remoteFileName, String localFileName) {
boolean flag =
true;
connectServer();
// 下載文件
BufferedOutputStream buffOut =
null;
try {
buffOut =
new BufferedOutputStream(
new FileOutputStream(localFileName));
flag = ftpClient.retrieveFile(remoteFileName, buffOut);
}
catch (Exception e) {
e.printStackTrace();
logger.debug(
"本地文件下載失敗!", e);
}
finally {
try {
if (buffOut !=
null)
buffOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 刪除一個文件
*/
public
static
boolean deleteFile(String filename) {
boolean flag =
true;
try {
connectServer();
flag = ftpClient.deleteFile(filename);
if (flag) {
System.out.println(
"刪除文件成功!");
}
else {
System.out.println(
"刪除文件失敗!");
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}
/**
* 刪除目錄
*/
public
static
void deleteDirectory(String pathname) {
try {
connectServer();
File file =
new File(pathname);
if (file.isDirectory()) {
File file2[] = file.listFiles();
}
else {
deleteFile(pathname);
}
ftpClient.removeDirectory(pathname);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 刪除空目錄
*/
public
static
void deleteEmptyDirectory(String pathname) {
try {
connectServer();
ftpClient.removeDirectory(pathname);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 列出服務器上文件和目錄
*
* @param regStr --匹配的正則表達式
*/
public
static
void listRemoteFiles(String regStr) {
connectServer();
try {
String files[] = ftpClient.listNames(regStr);
if (files ==
null || files.length == 0)
System.out.println(
"沒有任何文件!");
else {
for (
int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 列出Ftp服務器上的全部文件和目錄
*/
public
static
void listRemoteAllFiles() {
connectServer();
try {
String[] names = ftpClient.listNames();
for (
int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 關閉鏈接
*/
public
static
void closeConnect() {
try {
if (ftpClient !=
null) {
ftpClient.logout();
ftpClient.disconnect();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 設置配置文件
*
* @param configFile
*/
public
static
void setConfigFile(String configFile) {
FtpTest.configFile = configFile;
}
/**
* 設置傳輸文件的類型[文本文件或者二進制文件]
*
* @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE
*
*/
public
static
void setFileType(
int fileType) {
try {
connectServer();
ftpClient.setFileType(fileType);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 擴展使用
*
* @return ftpClient
*/
protected
static FTPClient getFtpClient() {
connectServer();
return ftpClient;
}
/**
* 設置參數
*
* @param configFile --參數的配置文件
*/
private
static
void setArg(String configFile) {
property =
new Properties();
BufferedInputStream inBuff =
null;
try {
File file =
new File(configFile);
inBuff =
new BufferedInputStream(
new FileInputStream(file));
property.load(inBuff);
userName = property.getProperty(
"username");
password = property.getProperty(
"password");
ip = property.getProperty(
"ip");
port = Integer.parseInt(property.getProperty(
"port"));
}
catch (FileNotFoundException e1) {
System.out.println(
"配置文件 " + configFile +
" 不存在!");
}
catch (IOException e) {
System.out.println(
"配置文件 " + configFile +
" 沒法讀取!");
}
}
/**
* 鏈接到服務器
*
* @return true 鏈接服務器成功,false 鏈接服務器失敗
*/
public
static
boolean connectServer() {
boolean flag =
true;
if (ftpClient ==
null) {
int reply;
try {
setArg(configFile);
ftpClient =
new FTPClient();
ftpClient.setControlEncoding(
"GBK");
ftpClient.setDefaultPort(port);
ftpClient.configure(getFtpConfig());
ftpClient.connect(ip);
ftpClient.login(userName, password);
ftpClient.setDefaultPort(port);
//System.out.print(ftpClient.getReplyString());
reply = ftpClient.getReplyCode();
ftpClient.setDataTimeout(120000);
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println(
"FTP server refused connection.");
// logger.debug("FTP 服務拒絕鏈接!");
flag =
false;
}
// System.out.println(i);
i++;
}
catch (SocketException e) {
flag =
false;
e.printStackTrace();
System.err.println(
"登陸ftp服務器 " + ip +
" 失敗,鏈接超時!");
}
catch (IOException e) {
flag =
false;
e.printStackTrace();
System.err.println(
"登陸ftp服務器 " + ip +
" 失敗,FTP服務器沒法打開!");
}
}
return flag;
}
/**
* 進入到服務器的某個目錄下
*
* @param directory
*/
public
static
void changeWorkingDirectory(String directory) {
try {
connectServer();
ftpClient.changeWorkingDirectory(directory);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 返回到上一層目錄
*/
public
static
void changeToParentDirectory() {
try {
connectServer();
ftpClient.changeToParentDirectory();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 重命名文件
*
* @param oldFileName --原文件名
* @param newFileName --新文件名
*/
public
static
void renameFile(String oldFileName, String newFileName) {
try {
connectServer();
ftpClient.rename(oldFileName, newFileName);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 設置FTP客服端的配置--通常能夠不設置
*
* @return ftpConfig
*/
private
static FTPClientConfig getFtpConfig() {
FTPClientConfig ftpConfig =
new FTPClientConfig(FTPClientConfig.SYST_UNIX);
ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
return ftpConfig;
}
/**
* 轉碼[ISO-8859-1 -> GBK] 不一樣的平臺須要不一樣的轉碼
*
* @param obj
* @return ""
*/
private
static String iso8859togbk(Object obj) {
try {
if (obj ==
null)
return "";
else
return
new String(obj.toString().getBytes(
"iso-8859-1"),
"GBK");
}
catch (Exception e) {
return "";
}
}
/**
* 在服務器上建立一個文件夾
*
* @param dir 文件夾名稱,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>...
*/
public
static
boolean makeDirectory(String dir) {
connectServer();
boolean flag =
true;
try {
// System.out.println("dir=======" dir);
flag = ftpClient.makeDirectory(dir);
if (flag) {
System.out.println(
"make Directory " + dir +
" succeed");
}
else {
System.out.println(
"make Directory " + dir +
" false");
}
}
catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}