1. 程式人生 > >ftp上傳下載解決負載均衡上傳下載問題

ftp上傳下載解決負載均衡上傳下載問題

注意問題:
首先linux安裝ftp伺服器
http://jingyan.baidu.com/article/7908e85c988b23af481ad2ae.html


上傳路徑要是:
1:建立ftp使用者的家目錄,使用sudo mkdir /home/ftp命令
2:設定ftp家目錄的許可權,我這裡為方便直接使用sudo chmod 777 /home/ftp命令將許可權設定為777,當然你    可以根據自己需求進行設定。
否則(vsftp上傳檔案出現553 Could not create file解決方法

對/etc/vsftpd.conf配置檔案進行一定的修改。


(1)修改/etc/vsftpd/vsftpd.conf---à去掉註釋 anon_upload_enable=YES 
(2)修改/etc/vsftpd/vsftpd.conf---à去掉註釋 anon_mkdir_write_enable=YES
anonymous_enable=YES     /允許匿名訪問 
提示:要想讓匿名使用者支援刪除和更名許可權,必須在vsftpd.conf加入以下引數

anon_other_write_enable=YES  允許匿名賬號具有刪除.更名許可權

設定完一定重啟:sudo service vsftpd restart

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.TreeSet;


import org.apache.commons.io.FileUtils;
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.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


public class FTPTools {


private String uid;
private String pwd;
private String hostname;


private boolean binaryTransfer = true;
private int port = 21;


public FTPTools(String uid, String pwd, String hostname) {
this.uid = uid;
this.pwd = pwd;
this.hostname = hostname;
}


public FTPTools(String uid, String pwd, String hostname, int port) {
this.uid = uid;
this.pwd = pwd;
this.hostname = hostname;
this.port = port;
}


/*
* getter & setter
*/
public boolean isBinaryTransfer() {
return binaryTransfer;
}


public void setBinaryTransfer(boolean binaryTransfer) {
this.binaryTransfer = binaryTransfer;
}


public int getPort() {
return port;
}


public void setPort(int port) {
this.port = port;
}


private FTPClient ftpClient = null;
private SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm");


private final String[] FILE_TYPES = { "檔案", "目錄", "符號連結", "未知型別" };


/**
* 設定FTP客服端的配置--一般可以不設定

* @return
*/
private FTPClientConfig getFtpConfig() {
FTPClientConfig ftpConfig = new FTPClientConfig(
FTPClientConfig.SYST_UNIX);
ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
return ftpConfig;
}


/**
* 連線到伺服器

* @throws IOException
*/
public void openConnect() {
int reply;
try {
// setArg(configFile);
ftpClient = new FTPClient();
ftpClient.setDefaultPort(port);
ftpClient.configure(getFtpConfig());
ftpClient.connect(hostname);
ftpClient.login(uid, pwd);
ftpClient.setControlEncoding("GB18030");
System.out.print(ftpClient.getReplyString());
reply = ftpClient.getReplyCode();


if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
// user.writeLog("【FTPTools】:FTP server refused connection.");
System.out.println("【FTPTools】:FTP server refused connection.");
} else {
if (ftpClient.login(uid, pwd)) {
// 設定為passive模式
ftpClient.enterLocalPassiveMode();
}
// user.writeLog("【FTPTools】:登入ftp伺服器[" + hostname+ "]成功");
System.out.println("【FTPTools】:登入ftp伺服器[" + hostname + "]成功");
System.out.println("【FTPTools】:當前目錄為"
+ ftpClient.printWorkingDirectory());
// user.writeLog("【FTPTools】:當前目錄為" +
// ftpClient.printWorkingDirectory());
}
} catch (Exception e) {
// user.writeLog("【FTPTools】:登入ftp伺服器[" + hostname + "]失敗");
System.out.println("【FTPTools】:登入ftp伺服器[" + hostname + "]失敗");
e.printStackTrace();
}
}


/**
* 關閉連線
*/
public void closeConnect() {
try {
if (ftpClient != null) {
ftpClient.logout();
System.out.print(ftpClient.getReplyString());
ftpClient.disconnect();
// user.writeLog("【FTPTools】:斷開ftp伺服器[" + hostname + "]成功");
System.out.println("【FTPTools】:斷開ftp伺服器[" + hostname + "]成功");
} else {
System.out.println("【FTPTools】:已經斷開ftp伺服器[" + hostname + "]");
// user.writeLog("【FTPTools】:已經斷開ftp伺服器[" + hostname + "]");
}


} catch (Exception e) {
e.printStackTrace();
// user.writeLog("【FTPTools】:斷開ftp伺服器[" + hostname + "]失敗");
System.out.println("【FTPTools】:斷開ftp伺服器[" + hostname + "]失敗");
}
}


/**
* 進入到伺服器的某個目錄下

* @param directory
*/
public void changeWorkingDirectory(String directory) {
try {


if (ftpClient == null) {
openConnect();
}
ftpClient.changeWorkingDirectory(directory);
System.out.print(ftpClient.getReplyString());
System.out.println("【FTPTools】:進入目錄" + directory);
System.out.println("【FTPTools】:當前目錄為"
+ ftpClient.printWorkingDirectory());
// user.writeLog("【FTPTools】:當前目錄為" +
// ftpClient.printWorkingDirectory());
// user.writeLog(ftpClient.getReplyString());
// user.writeLog("【FTPTools】:進入目錄" + directory);
} catch (IOException ioe) {
ioe.printStackTrace();
// user.writeLog(ioe);
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 返回到上一層目錄
*/
public void changeToParentDirectory() {
try {
if (ftpClient == null) {
openConnect();
}
ftpClient.changeToParentDirectory();
System.out.print(ftpClient.getReplyString());
System.out.println("【FTPTools】:返回至上層目錄");
System.out.println("【FTPTools】:當前目錄為"
+ ftpClient.printWorkingDirectory());
// user.writeLog("【FTPTools】:當前目錄為" +
// ftpClient.printWorkingDirectory());
// user.writeLog(ftpClient.getReplyString());
// user.writeLog("【FTPTools】:返回至上層目錄");
} catch (IOException ioe) {
ioe.printStackTrace();
// user.writeLog(ioe);
}
}


/**
* 列出伺服器上所有檔案及目錄
*/
public void listAllRemoteFiles() {
listRemoteFiles("*");
}


/**
* 列出伺服器上檔案和目錄

* @param regStr
*            --匹配的正則表示式
*/
// @SuppressWarnings("unchecked")
@SuppressWarnings(value = { "unchecked" })
public void listRemoteFiles(String regStr) {
checkConnect(ftpClient);
try {
FTPFile[] files = ftpClient.listFiles(regStr);
System.out.print(ftpClient.getReplyString());
if (files == null || files.length == 0) {
System.out.println("【FTPTools】:There has not any file!");
// user.writeLog("【FTPTools】:There has not any file!");
} else {
TreeSet<FTPFile> fileTree = new TreeSet(new Comparator() {
// 先按照檔案的型別排序(倒排),然後按檔名順序排序
public int compare(Object objFile1, Object objFile2) {
if (objFile1 == null) {
return -1;
} else if (objFile2 == null) {
return 1;
} else {
FTPFile file1 = (FTPFile) objFile1;
FTPFile file2 = (FTPFile) objFile2;
if (file1.getType() != file2.getType()) {
return file2.getType() - file1.getType();
} else {
return file1.getName().compareTo(
file2.getName());
}
}
}
});
for (FTPFile file : files) {
fileTree.add(file);
}
System.out.printf("%-35s%-10s%15s%15s/n", "名稱", "型別", "修改日期",
"大小");
for (FTPFile file : fileTree) {
System.out.printf("%-35s%-10s%15s%15s/n",
iso8859togbk(file.getName()),
FILE_TYPES[file.getType()],
dateFormat.format(file.getTimestamp().getTime()),
FileUtils.byteCountToDisplaySize(file.getSize()));
}
}
} catch (Exception e) {
e.printStackTrace();
// user.writeLog(e);
}
}


/**
* 設定傳輸檔案的型別[文字檔案或者二進位制檔案]

* @param fileType
*            --BINARY_FILE_TYPE、ASCII_FILE_TYPE
*/
public void setFileType(int fileType) {
try {
if (ftpClient == null) {
openConnect();
}
ftpClient.setFileType(fileType);
} catch (Exception e) {
e.printStackTrace();
// user.writeLog(e);
}
}


/**
* 轉碼[ISO-8859-1 -> GBK] 不同的平臺需要不同的轉碼

* @param obj
* @return
*/
private String iso8859togbk(Object obj) {
try {
if (obj == null) {
return "要轉換的物件為null";
} else {
return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
}
} catch (Exception e) {
return e.toString();
}
}


/**
* 刪除檔案
*/
public void deleteFile(String filename) {
try {
if (ftpClient == null) {
openConnect();
}
ftpClient.deleteFile(filename);
System.out.print(ftpClient.getReplyString());
System.out.println("【FTPTools】:刪除檔案" + filename + "成功!");
// user.writeLog(ftpClient.getReplyString());
// user.writeLog("【FTPTools】:刪除檔案" + filename + "成功!");
} catch (IOException ioe) {
ioe.printStackTrace();
// user.writeLog("【FTPTools】:刪除檔案" + filename + "失敗!");
System.out.println("【FTPTools】:刪除檔案" + filename + "失敗!");
}
}


/**
* 重新命名檔案

* @param oldFileName
*            --原檔名
* @param newFileName
*            --新檔名
*/
public void renameFile(String oldFileName, String newFileName) {
try {
if (ftpClient == null) {
openConnect();
}
ftpClient.rename(oldFileName, newFileName);
System.out.print(ftpClient.getReplyString());
System.out.println("【FTPTools】:將檔案" + oldFileName + "重新命名為"
+ newFileName);
// user.writeLog(ftpClient.getReplyString());
// user.writeLog("【FTPTools】:將檔案" + oldFileName + "重新命名為"+
// newFileName);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}


/**
* 上傳檔案

* @param localFilePath
*            --本地檔案路徑
* @param newFileName
*            --新的檔名
*/
public boolean uploadFile(String localFilePath, String localFileName,
String remoteFilePath, String remoteFileName) {
checkConnect(ftpClient);
if (!localFilePath.endsWith("/")) {
localFilePath += "/";
}
transferType(binaryTransfer);
int reply;


// 上傳檔案
BufferedInputStream bis = null;
try {
ftpClient.changeWorkingDirectory(remoteFilePath);
reply = ftpClient.getReplyCode();
if (reply == 550) {
ftpClient.makeDirectory(remoteFilePath);
ftpClient.changeWorkingDirectory(remoteFilePath);
}


bis = new BufferedInputStream(new FileInputStream(localFilePath
+ localFileName));
boolean bb = ftpClient.storeFile(remoteFileName, bis);
System.out.println(ftpClient.getReplyString() + "【FTPTools】:上傳檔案"
+ localFilePath + localFileName + "成功!");
return true;
} catch (Exception e) {
System.out.println("【FTPTools】:上傳檔案" + localFilePath
+ localFileName + "失敗!");
System.out.println(e.toString());
return false;
} finally {
try {
if (bis != null) {
bis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}


/**
* 下載檔案

* @param remoteFileName
*            --伺服器上的檔名
* @param localFileName
*            --本地檔名
*/
public boolean loadFile(String remoteFilePath, String remoteFileName,
String localFilePath, String localFileName) {
checkConnect(ftpClient);
if (!remoteFilePath.endsWith("/")) {
remoteFilePath += "/";
}
if (!localFilePath.endsWith("/")) {
localFilePath += "/";
}
transferType(binaryTransfer);
if (localFileName == "" || localFileName == null) {
localFileName = remoteFileName;
}
// 下載檔案
BufferedOutputStream bos = null;
try {
if (remoteFilePath != "" && remoteFilePath != null) {
changeWorkingDirectory(remoteFilePath);
}
System.out.println("【FTPTools】:開始下載檔案到" + localFilePath
+ localFileName);
// user.writeLog(ftpClient.getReplyString());
if (isExist(remoteFileName)) {
bos = new BufferedOutputStream(new FileOutputStream(
localFilePath + localFileName));
ftpClient.retrieveFile(remoteFileName, bos);
System.out.print(ftpClient.getReplyString());
System.out.println("【FTPTools】:下載檔案" + remoteFilePath
+ remoteFileName + "成功!");
return true;
} else {
System.out.println("【FTPTools】:檔案" + remoteFilePath
+ remoteFileName + "不存在!");
System.out.println("【FTPTools】:下載檔案" + remoteFilePath
+ remoteFileName + "失敗!");
return false;
}
} catch (Exception e) {
System.out.println(ftpClient.getReplyString() + "【FTPTools】:下載檔案"
+ remoteFilePath + remoteFileName + "失敗!");
System.out.println(String.valueOf(e));
return false;
} finally {
try {
if (bos != null)
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


/**
* 設定檔案傳輸型別

* @param binaryTransfer
* @throws IOException
*/
public void transferType(boolean binaryTransfer) {
try {
if (binaryTransfer) {
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
} else {
ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
}
} catch (IOException e) {
e.printStackTrace();
}
}


/**
* 檢查遠端檔案是否存在

* @param remoteFileName
* @return
*/
@SuppressWarnings("unchecked")
public boolean checkFileName(String remotePath, String remoteFileName) {
checkConnect(ftpClient);
changeWorkingDirectory(remotePath);
boolean result = false;
try {
FTPFile[] files = ftpClient.listFiles("*");
System.out.print(ftpClient.getReplyString());
if (files == null || files.length == 0) {
System.out.println("【FTPTools】:There has not any file!");
// user.writeLog("【FTPTools】:There has not any file!");
} else {
TreeSet<FTPFile> fileTree = new TreeSet(new Comparator() {
// 先按照檔案的型別排序(倒排),然後按檔名順序排序
public int compare(Object objFile1, Object objFile2) {
if (objFile1 == null) {
return -1;
} else if (objFile2 == null) {
return 1;
} else {
FTPFile file1 = (FTPFile) objFile1;
FTPFile file2 = (FTPFile) objFile2;
if (file1.getType() != file2.getType()) {
return file2.getType() - file1.getType();
} else {
return file1.getName().compareTo(
file2.getName());
}
}
}
});
for (FTPFile file : files) {
fileTree.add(file);
}
for (FTPFile file : fileTree) {
if (file.getName().equals(remoteFileName)) {
result = true;
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
changeToParentDirectory();
return result;
}


/**
* 檢測檔案或資料夾是否存在

* @param fileName
*            --檔案或資料夾名稱
* @return
*/
public boolean isExist(String fileName) {
checkConnect(ftpClient);
boolean tmp = false;
try {
System.out.println("【FTPTools】:當前目錄為"
+ ftpClient.printWorkingDirectory());
// user.writeLog("【FTPTools】:當前目錄為" +
// ftpClient.printWorkingDirectory());
String[] strs = ftpClient.listNames();
for (int i = 0; i < strs.length; i++) {
if (strs[i].equals(fileName)) {
tmp = true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return tmp;
}


public void checkConnect() {
checkConnect(this.ftpClient);
}


private void checkConnect(FTPClient ftpClient) {
if (ftpClient == null) {
openConnect();
} else {
try {
ftpClient.stat();
} catch (IOException e) {
try {
ftpClient.setDefaultPort(port);
ftpClient.configure(getFtpConfig());
ftpClient.connect(hostname);
ftpClient.login(uid, pwd);
ftpClient.setControlEncoding("GB18030");
System.out.print(ftpClient.getReplyString());
int reply = ftpClient.getReplyCode();


if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
// user.writeLog("【FTPTools】:FTP server refused connection.");
System.out
.println("【FTPTools】:FTP server refused connection.");
} else {
if (ftpClient.login(uid, pwd)) {
// 設定為passive模式
ftpClient.enterLocalPassiveMode();
}
// user.writeLog("【FTPTools】:登入ftp伺服器[" + hostname+
// "]成功");
System.out.println("【FTPTools】:登入ftp伺服器[" + hostname
+ "]成功");
System.out.println("【FTPTools】:當前目錄為"
+ ftpClient.printWorkingDirectory());
// user.writeLog("【FTPTools】:當前目錄為" +
// ftpClient.printWorkingDirectory());
}
} catch (Exception e2) {
// user.writeLog("【FTPTools】:登入ftp伺服器[" + hostname + "]失敗");
System.out.println("【FTPTools】:登入ftp伺服器[" + hostname
+ "]失敗");
e2.printStackTrace();
}
}
}
}


/**
* 測試

* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FTPTools ftp = new FTPTools("admin1", "admin", "192.168.190.129");
// ftp.loadFile("/", "222.txt", "D:/", "");
ftp.uploadFile("D:/", "111.txt", "/home/ftp", "222.txt");
ftp.closeConnect();
}


}