Java 操作FTP

package com.smartelevatorguard.hot.common.utils;

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 com.smartelevatorguard.hot.common.communication.ConfigMapper;

import java.io.*;
import java.net.SocketException;
import java.util.Date;


public class Ftp {
public static Log logger = LogFactory.getLog(Ftp.class);

//FTP 地址
private static final String ftpIp = ConfigMapper.fetch("ftp.intranet.ip");
//FTP端口
private static final Integer ftpPort= Integer.parseInt(ConfigMapper.fetch("ftp.port"));
//FTP登录用户名
private static final String account = ConfigMapper.fetch("ftp.account");
//FTP登录密码
private static final String password = ConfigMapper.fetch("ftp.pwd");
//FTP存储文件的路径
private static final String rootPath = ConfigMapper.fetch("ftp.zx.weibao");
//下载或者删除要用到绝对路径
private static final String downOrDel = ConfigMapper.fetch("ftp.zx.weibao.downOrDel");

private static FTPClient ftpClient = null; //FTP 客户端代理

//FTP状态码
public static int i = 1;

public static void main(String[] args) {
// connectServer();
// setFileType(FTP.BINARY_FILE_TYPE);// 设置传输二进制文件
//上传文件
uploadFile(new File("E:\\images\\中秀文档.txt"), "", "zhongxiu4/test");
//删除文件
//deleteFile("/var/ftp"+rootPath+"zhongxiu2"+"/中秀logo中秀文档.txt");
//删除文件目录
// deleteDirectory("/var/ftp"+rootPath+"zhongxiu2");
//下载文件
// loadFile(downOrDel+"zhongxiu2/中秀文档.txt","E://images//1122111.txt");
// closeConnect();// 关闭连接
System.out.println(new Date().getTime());
}


/**
* @Title: uploadFile
* @Description 描述: 上传单个文件
* @param 参数:@param localFile::文件地址
* @param 参数:@param newFileName:新的文件名称(可为空)
* @param 参数:@param directoryFolder
* @param 参数:@return
* @return 返回类型 : boolean
* @author
* @date 创建时间:2016年6月22日 下午12:47:36
* @throws
*/
public static boolean uploadFile(File localFile, String newFileName, final String directoryFolder) {
boolean flag = true;
try {
connectServer();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
InputStream input = new FileInputStream(localFile);

ftpClient.changeWorkingDirectory(rootPath);
String[] sourceStrArray = directoryFolder.split("/");
//如果文件夹创建失败,文件将会放到父目录下面
for (int i = 0; i < sourceStrArray.length; i++) {
boolean f =ftpClient.makeDirectory(sourceStrArray[i]);
ftpClient.changeWorkingDirectory(sourceStrArray[i]);
}

logger.debug("begin upload:" + localFile.getPath() + "----To--- " + ftpClient.printWorkingDirectory());
flag = ftpClient.storeFile(newFileName+localFile.getName(), input);
if (flag) {
logger.debug("上传:"+localFile.getPath()+"-----成功");
} else {
logger.debug("上传:"+localFile.getPath()+"-----失败");

}
input.close();
} catch (IOException e) {
e.printStackTrace();
logger.debug("本地文件上传失败!", e);
flag = false;
return flag;
} catch (Exception e) {
e.printStackTrace();
flag = false;
return flag;
}
return flag;
}

/**
* @Title: uploadFileInputStream
* @Description 描述: FTP上传文件,并创建文件夹
* @param 参数:@param input:文件流
* @param 参数:@param newFileName:新的文件名字
* @param 参数:@param directoryFolder:文件夹目录
* @param 参数:@return
* @return 返回类型 : boolean
* @author
* @date 创建时间:2016年6月23日 上午10:39:30
* @throws
*/
public static boolean uploadFileInputStream(InputStream input, String newFileName, final String directoryFolder) {
boolean flag = true;
try {
connectServer();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
ftpClient.changeWorkingDirectory(rootPath);
//循环创建目录
String[] sourceStrArray = directoryFolder.split("/");
//如果文件夹创建失败,文件将会放到父目录下面
for (int i = 0; i < sourceStrArray.length; i++) {
boolean f =ftpClient.makeDirectory(sourceStrArray[i]);
ftpClient.changeWorkingDirectory(sourceStrArray[i]);
}

logger.debug("begin upload:" + newFileName + "----To--- " + ftpClient.printWorkingDirectory());
flag = ftpClient.storeFile(newFileName, input);
if (flag) {
logger.debug("上传:"+newFileName+"-----成功");
} else {
logger.debug("上传:"+newFileName+"-----失败");

}
input.close();
} catch (IOException e) {
e.printStackTrace();
logger.debug("本地文件上传失败!", e);
flag = false;
return flag;
} catch (Exception e) {
e.printStackTrace();
flag = false;
return flag;
}
return flag;
}
/**
* 下载文件
*
* @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) {
logger.debug(filename+"删除文件成功");
} else {
logger.debug(filename+"删除文件失败!");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}

/**
* 删除目录
*/
public static void deleteDirectory(String pathname) {
try {
connectServer();
File file = new File(pathname);
System.out.println(file.isDirectory());
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();
}
}

/**
* 关闭连接
*/
public static void closeConnect() {
try {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 设置传输文件的类型[文本文件或者二进制文件]
*
* @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;
}


/**
* 连接到服务器
*
* @return true 连接服务器成功,false 连接服务器失败
*/
public static boolean connectServer() {
boolean flag = true;
if (ftpClient == null) {
int reply;
try {

ftpClient = new FTPClient();
ftpClient.setControlEncoding("GBK");
//ftpClient.setDefaultPort(ftpPort);
//ftpClient.configure(getFtpConfig());
ftpClient.connect(ftpIp);
ftpClient.login(account, password);
ftpClient.setDefaultPort(ftpPort);
//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();
logger.debug("登录ftp服务器 " + ftpIp + " 失败,连接超时!");
} catch (IOException e) {
flag = false;
e.printStackTrace();
logger.debug("登录ftp服务器 " + ftpIp + " 失败,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;
}

}

你可能感兴趣的:(java,java)