Ftp.java
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;
import sun.net.ftp.FtpClient;
/**
* ftp上传
*
*/
public class Ftp {
private String ip = "";
private String username = "";
private String password = "";
private int port = 21;
private String localFileFullName = "";//需要上传的目录
FtpClient ftpClient = null;
public FtpClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FtpClient ftpClient) {
this.ftpClient = ftpClient;
}
OutputStream os = null;
FileInputStream is = null;
public Ftp(String serverIP, int port , String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
this.port = port;
}
public Ftp(String serverIP,String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
}
/**
* 创建文件夹
* @param dir
* @param ftpClient
* @throws Exception
*/
public void createDir(String dir, FtpClient ftpClient) throws Exception {
ftpClient.ascii();
StringTokenizer s = new StringTokenizer(dir, "/"); //sign
s.countTokens();
String pathName = "";
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpClient.sendServer("MKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
}
ftpClient.readServerResponse();
}
ftpClient.binary();
}
/**
* 检查文件夹是否存在
* @param dir
* @param ftpClient
* @return
*/
private Boolean isDirExist(String dir, FtpClient ftpClient) {
try {
ftpClient.cd(dir);
} catch (Exception e) {
return false;
}
return true;
}
/**
* ftp上传
* @param localFileFullName 上传的源文件夹
* @return
*/
public Boolean upload(String localFileFullName) {
this.localFileFullName = localFileFullName;
try {
String savefilename = new String(localFileFullName.getBytes("ISO-8859-1"), "GBK");
//新建一个FTP客户端连接
ftpClient = new FtpClient();
ftpClient.openServer(this.ip,this.port);
ftpClient.login(this.username, this.password);
//打开本地待长传的文件
File file_in = new File(savefilename);
processFile(file_in,ftpClient);
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (ftpClient != null) {
ftpClient.closeServer();
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception e in Ftp upload(): " + e.toString());
return false;
}
}
/**
* ftp上传
* @param localFileFullName 上传的源文件夹
* @return
* @throws Exception
*/
public void uploadSlsFtp(String localFileFullName) throws Exception {
this.localFileFullName = localFileFullName;
String savefilename = new String(localFileFullName.getBytes("ISO-8859-1"), "GBK");
//打开本地待长传的文件
File file_in = new File(savefilename);
processFile(file_in,ftpClient);
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (ftpClient != null) {
ftpClient.closeServer();
}
}
/**
* 上传文件
* @param source
* @param ftpClient
* @throws Exception
*/
private void processFile(File source,FtpClient ftpClient) throws Exception{
if (source.exists()) {
if (source.isDirectory()) {
if (!isDirExist(source.getPath().substring(localFileFullName.length()).replace("\\", "/"), ftpClient)) {
createDir(source.getPath().substring(localFileFullName.length()).replace("\\", "/"), ftpClient);
}
File sourceFile[] = source.listFiles();
for (int i = 0; i < sourceFile.length; i++) {
if (sourceFile[i].exists()) {
if (sourceFile[i].isDirectory()) {
this.processFile(sourceFile[i],ftpClient);
} else {
ftpClient.cd(cheangPath(sourceFile[i].getPath()));
ftpClient.binary();
os = ftpClient.put(sourceFile[i].getName());
byte[] bytes = new byte[1024];
is = new FileInputStream(sourceFile[i]);
//开始复制
int c;
//暂未考虑中途终止的情况
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
is.close();
os.close();
}
}
}
} else {
ftpClient.cd(cheangPath(source.getPath()));
ftpClient.binary();
os = ftpClient.put(source.getName());
byte[] bytes = new byte[1024];
is = new FileInputStream(source);
//开始复制
int c;
//暂未考虑中途终止的情况
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
is.close();
os.close();
}
} else {
throw new Exception("此文件或文件夹[" + source.getName() + "]有误或不存在!");
}
}
/**
* 获取当前的FTP路径
* @param path
* @return
*/
private String cheangPath(String path){
path = path.substring(localFileFullName.length()).replace("\\", "/");
if("".equals(path)){
path = "/";
}else{
path = path.substring(0,path.lastIndexOf("/")+1);
}
return path;
}
public static void main(String args[]) throws Exception {
Ftp ftpup = new Ftp("10.225.2.174",21,"ossftp","ossftp");
ftpup.upload("D:/Tomcat6.0/webapps/oss/ftpfiles"); //
FtpDownFiles.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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;
import com.tansun.easycare.util.DateUtil;
import cn.com.cbhb.amp.util.SystemConfig;
/*******************************************************************************
* 功能说明: 从ftp服务器指定目录复制文件到本地指定路径
*
******************************************************************************/
public class FtpDownFiles {
private FTPClient ftpClient;
public FtpDownFiles() {
this.ftpClient = new FTPClient();
}
/**
* 功能说明:通过递归实现ftp目录文件与本地文件同步更新,返回1-成功或未执行操作;0-失败
*
* @param ftpfilepath
* 当前ftp目录
* @param localpath
* 当前本地目录
* @throws Exception
*/
public void ftpDownFiles(String ftpfilepath, String localpath, List list) throws Exception {
if (!localpath.endsWith("/")) {
localpath = localpath + "/";
}
FTPFile[] ff = ftpClient.listFiles(ftpfilepath);
int fflength = ff.length;
if (null != ff && fflength > 0) {
for (int i = 0; i < fflength; i++) {
String localfilepath = localpath + ff[i].getName();
File localFile = new File(localfilepath);
Date fflastModifiedDate = ff[i].getTimestamp().getTime();
Date localLastModifiedDate = new Date(localFile
.lastModified());
int result = localLastModifiedDate
.compareTo(fflastModifiedDate);
if (ff[i].isDirectory()) {
localFile.mkdir();
String ftpfp = ftpfilepath + ff[i].getName() + "/";
String localfp = localfilepath + "/";
this.ftpDownFiles(ftpfp, localfp, list);
} else if (ff[i].isFile()) {
if (ff[i].getSize() != localFile.length() || result < 0) {
String filepath = ftpfilepath + ff[i].getName();
FileOutputStream fos = new FileOutputStream(localFile);
filepath = new String(filepath.getBytes("GBK"),"ISO-8859-1");
System.out.println(filepath);
//测试异常使用
//disConnectServer();
boolean boo = ftpClient.retrieveFile(filepath, fos);
if (localFile.getPath() != null) {
if (localFile.getPath().indexOf("xml") > -1) {
String aaa = localFile
.getPath()
.substring(
localFile.getPath()
.indexOf("xml") - 1,
localFile.getPath()
.length());
if (aaa.equals(".xml")) {
list.add(localFile.getPath());
}
System.out.println();
}
}
if (boo == true) {
String name = ff[i].getName();
String dir = localpath;
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String time = sdf.format(localFile
.lastModified());
}
fos.flush();
fos.close();
} else {
}
}
}
} else {
}
}
public void connectServer(String hostip, String username, String password,
int port) {
try {
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
conf.setServerLanguageCode("zh");
ftpClient.configure(conf);
ftpClient.connect(hostip, port);
ftpClient.login(username, password);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
}
ftpClient.setControlEncoding("GBK");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
} catch (Exception e) {
e.printStackTrace();
}
}
public void ftpChangeWorkDirDownFiles(String ftpfilepath, String localpath, List list) throws Exception {
System.out.println("Now WorkingDirectory is:" + ftpClient.printWorkingDirectory());
if (!localpath.endsWith("/")) {
localpath = localpath + "/";
}
boolean res = ftpClient.changeWorkingDirectory(ftpfilepath);
System.out.println("Now WorkingDirectory is:" + ftpClient.printWorkingDirectory());
FTPFile[] ff = null;
if(res) {
ff = ftpClient.listFiles();
} else {
return;
}
int fflength = ff.length;
if (null != ff && fflength > 0) {
for (int i = 0; i < fflength; i++) {
String localfilepath = localpath + ff[i].getName();
File localFile = new File(localfilepath);
Date fflastModifiedDate = ff[i].getTimestamp().getTime();
Date localLastModifiedDate = new Date(localFile
.lastModified());
int result = localLastModifiedDate
.compareTo(fflastModifiedDate);
if (ff[i].isDirectory()) {
localFile.mkdir();
String ftpfp = ff[i].getName();
String localfp = localfilepath + "/";
this.ftpChangeWorkDirDownFiles(ftpfp, localfp, list);
} else if (ff[i].isFile()) {
if (ff[i].getSize() != localFile.length() || result < 0) {
//String filepath = ftpfilepath + ff[i].getName();
String filepath = ff[i].getName();
FileOutputStream fos = new FileOutputStream(localFile);
filepath = new String(filepath.getBytes("GBK"),"ISO-8859-1");
System.out.println(filepath);
//测试异常使用
//disConnectServer();
boolean boo = ftpClient.retrieveFile(filepath, fos);
if (localFile.getPath() != null) {
if (localFile.getPath().indexOf("xml") > -1) {
String aaa = localFile
.getPath()
.substring(
localFile.getPath()
.indexOf("xml") - 1,
localFile.getPath()
.length());
if (aaa.equals(".xml")) {
list.add(localFile.getPath());
}
System.out.println();
}
}
if (boo == true) {
String name = ff[i].getName();
String dir = localpath;
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String time = sdf.format(localFile
.lastModified());
}
fos.flush();
fos.close();
} else {
}
}
}
} else {
}
}
public void disConnectServer(){
try {
ftpClient.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
FtpDownFiles fd = new FtpDownFiles();
fd.connectServer(SystemConfig.getInstance().getProperty("EXTFTPFILESERVERIP"), SystemConfig.getInstance().getProperty("EXTFTPFILESERVERUSER"), SystemConfig.getInstance().getProperty("EXTFTPFILESERVERPASSWORD"),SystemConfig.getInstance().getIntValue("EXTFTPFILESERVERPORT"));
List list = new ArrayList();
String importpath ="/"+ DateUtil.formatDate2Str(DateUtil.getNextDay(new Date()),"yyyyMMdd")+"/";
//String importpath =DateUtil.formatDate2Str(DateUtil.getNextDay(new Date()),"yyyyMMdd");
try {
fd.ftpDownFiles(importpath,"c:/aaa/",list);
//fd.ftpChangeWorkDirDownFiles(importpath,"c:/aaa/",list);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
FtpFile.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.File;
import java.io.FileInputStream;
import cn.com.cbhb.amp.common.BizAuth;
import cn.com.cbhb.amp.util.SystemConfig;
public class FtpFile {
private static final Log log = LogFactory.getLog(FtpFile.class);
private FTPClient fc;
private String ip = SystemConfig.getInstance().getProperty("FTPFILESERVERIP");
private int port = SystemConfig.getInstance().getIntValue("FTPFILESERVERPORT");
private String userName = SystemConfig.getInstance().getProperty("FTPFILESERVERUSER");;
private String password = SystemConfig.getInstance().getProperty("FTPFILESERVERPASSWORD");;
public FtpFile() {
super();
}
public FtpFile(String ip, int port, String userName, String password) throws Exception {
super();
this.ip = ip;
this.port = port;
this.userName = userName;
this.password = password;
this.connectServer();
}
/**
* 连接到ftp
* @param ip
* FTP的IP地址
* @param port
* FTP的端口号
* @param userName
* 登录FTP地址的用户名
* @param password
* 登录FTP地址的密码
* @throws Exception
*/
public void connectServer() throws Exception {
try {
fc = new FTPClient();
if (port == 0) {
port = 21;
}
fc.connect(ip, port);
fc.login(userName, password);
fc.setFileType(FTPClient.BINARY_FILE_TYPE);
log.info("成功连接ftp服务器:" + createUrl(BizAuth.AUTH_ID_DOWNLOAD));
System.out.println("成功连接ftp服务器:" + createUrl(BizAuth.AUTH_ID_DOWNLOAD));
} catch (Exception e) {
log.error("ftp服务器连接失败",e);
throw new Exception(e);
}
}
/**
*
* @param file 上传的文件或文件夹
* @throws Exception
*/
public void uploadForder(File forder) throws Exception{
if(forder.isDirectory()){
fc.makeDirectory(forder.getName());
fc.changeWorkingDirectory(forder.getName());
String[] files = forder.list();
for (int i = 0; i < files.length; i++) {
File file1 = new File(forder.getPath()+System.getProperty("file.separator")+files[i] );
if(file1.isDirectory()){
uploadForder(file1);
fc.changeToParentDirectory();
}else{
File file2 = new File(forder.getPath()+System.getProperty("file.separator")+files[i]);
FileInputStream input = new FileInputStream(file2);
fc.storeFile(file2.getName(), input);
input.close();
}
}
}else{
File file2 = new File(forder.getPath());
FileInputStream input = new FileInputStream(file2);
fc.storeFile(file2.getName(), input);
input.close();
}
}
/**
* 上传文件到ftp
*
* @param in
* 本地文件
* @param remoteFile
* 服务器上的文件名
* @throws Exception
*/
public void uploadFile(InputStream in, String remoteFile) throws Exception {
try {
System.out.print(fc.getReplyString());
Integer reply = fc.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
fc.disconnect();
return;
}
fc.setFileType(FTPClient.BINARY_FILE_TYPE);
fc.storeUniqueFile(remoteFile, in);
} catch (IOException e) {
log.error("文件上传失败 上传到服务器的文件名:" + remoteFile,e);
throw new Exception(e);
}finally{
if(in != null){
IOUtils.closeQuietly(in);
}
}
}
/**
* 下载ftp上的文件
*
* @param outFileStream
* 下载到本地的文件流
* @param remoteFile
* 服务器上的文件名
* @throws Exception
*
*/
public void downLoadFile(FileOutputStream outFileStream, String remoteFile) throws Exception {
try {
fc.retrieveFile(remoteFile, outFileStream);
} catch (IOException e) {
log.error("文件下载失败 下载到服务器的文件名:" + remoteFile,e);
throw new Exception(e);
}
}
/**
* 删除ftp上的文件
*
* @param url
* 要删除的文件名
* @throws Exception
*/
public boolean deleteFile(String url) throws Exception {
int status = 0;
try {
status = fc.sendCommand(url);
log.info("远程执行命令: " + url + "\r\n");
return true;
} catch (IOException e) {
log.error("远程执行命令失败:" + url,e);
throw new Exception(e);
}finally{
if (status == 250) {
return true;
}
}
}
/**
* 关闭FTP服务
* @throws Exception
*/
public void closeServer() throws Exception {
try {
fc.logout();
} catch (IOException e) {
log.error("关闭ftp连接时出错:",e);
throw new Exception(e);
} finally {
if (fc.isConnected()) {
fc.disconnect();
}
}
}
/**
* 创建下载或者阅读时的ftp Url
* @return
*/
public static String createUrl(Integer bizauth){
FtpFile ftpFile = new FtpFile();
StringBuffer url = new StringBuffer("ftp://");
if(bizauth == BizAuth.AUTH_ID_DOWNLOAD){
url.append( ftpFile.getUserName() + ":" + ftpFile.getPassword() + "@" + ftpFile.getIp() + ":" + ftpFile.getPort() + "/");
}else if(bizauth == BizAuth.AUTH_ID_LOOK){
url.append( ftpFile.getIp() + ":" + ftpFile.getPort() + "/");
}
return url.toString();
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public FTPClient getFc() {
return fc;
}
public void setFc(FTPClient fc) {
this.fc = fc;
}
public static void main(String[] args) {
String ip = SystemConfig.getInstance().getProperty("FTPFILESERVERIP");
int port = SystemConfig.getInstance().getIntValue("FTPFILESERVERPORT");
String userName = SystemConfig.getInstance().getProperty("FTPFILESERVERUSER");;
String password = SystemConfig.getInstance().getProperty("FTPFILESERVERPASSWORD");;
FtpFile ftp;
try {
ftp = new FtpFile(ip,port,userName,password);
// ftp.downLoadFile(outFileStream, remoteFile);
System.out.println(ftp.getIp());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// ftp.downLoadFile(outFileStream, remoteFile)
}
}