ftp上传下载解决负载均衡上传下载问题
注意问题:首先linux安装ftp服务器http://jingyan.baidu.com/article/7908e85c988b23af481ad2ae.html上传路径要是:1:创建ftp用户的家目录,使用sudo mkdir /home/ftp命令2:设置ftp家目录的权限,我这里为方便直接使用sudo chmod 777 /home/ftp命令将权限设置为777
首先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();
}
}
更多推荐
所有评论(0)