System.out.println("NOTE: Source files will be deleted after successful transfer!"); System.out.println("Use archiving function to retain a copy of files"); System.out.println("\nUsage : java -jar ftpAgent.jar ATTRIBUTES"); System.out.println("Example: java -jar ftpAgent.jar -o p -v 192.168.0.1 -u user -p myPassword -s ./source -d ./dest -a s"); System.out.println("\nAttribute = PREFIX ARGUMENT"); System.out.println("Prefixes \t\tArguments"); System.out.println("-o --operation\t\t g|p type of operation: g to get files from server or p to put files on server"); System.out.println("-v --ftp server\t\t server address"); System.out.println("-u --ftp user\t\t ftp account user name"); System.out.println("-p --password\t\t ftp account password"); System.out.println("-s --source\t\t source directory"); System.out.println("-d --destination\t destination directory"); System.out.println("-a --achiving options\t n|s|d|b n-no archiving, s-archive source, d-archive destination, b-both"); System.out.println("\nAlternative: java -jar ftpAgent.jar OPERATION SERVER USER PASSWORD SOURCE_DIRECTORY DESTINATION_DIRECTORY ARCHIVING"); System.out.println("Example: java -jar ftpAgent.jar p 192.168.0.1 user myPassword ./source ./dest s"); }
/* * get files from sourceDir in the source ftp server using username and password * and store in destDir. If sourceArchive and or destArchive are given then a copy * of downloaded files are archived in the respective directories * */
public FtpAgent() { ftp = new FTPClient(); } 待续......
server = sourceServer; user = userName; password = pw;
List recvFiles = null; File dir = null; String destArchDir = null;
Calendar cal = new GregorianCalendar(); SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd"); String archiveDir = dFormat.format(cal.getTime()) + File.separator;
if (!destDir.endsWith(File.separator) && !destDir.equals("")) destDir = destDir.concat(File.separator); dir = new File(destDir); if (!dir.exists()) { dir.mkdir(); }
if (archiveDest) { String remoteArchDir = destDir + archiveDir; if (_log.isDebugEnabled()) _log.debug("remote archive: " + remoteArchDir); performPutFiles(fileList, remoteArchDir, overwrite); }
} catch (FTPConnectionClosedException e) { _log.error("Premature disconnection of server: " + destServer, e); throw new FTPConnectionClosedException("Premature disconnection of server: " + destServer + "\n" + e.getLocalizedMessage()); } catch (IOException e) { _log.error("IO Error on putting files on server:" + destServer, e); throw new IOException("IO Error putting files on server:" + destServer + "\n" + e.getLocalizedMessage()); } finally { if (ftp != null) disconnectFTP(); }
// Copy downloaded files to source archive if required if (archiveSource) { String sourceArchDir = sourceDir + archiveDir; performLocalArchive(fileList, sourceArchDir); }
if (cleanup) { performLocalDelete(fileList); } }
/* * Takes a list of file paths and puts them on remote ftp server */ public void putFiles(String destServer, String userName, String pw, List sourcePaths, boolean archiveSource, boolean cleanup, String destDir, boolean archiveDest, boolean overwrite) throws InvalidFTPServerException, InvalidFTPAccountException, InvalidFileException,ArchiveException,IOException, SocketException, Exception {
server = destServer; user = userName; password = pw;
List fileList = new ArrayList(); String sourceArchDir = null;
Calendar cal = new GregorianCalendar(); SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd"); String archiveDir = dFormat.format(cal.getTime()) + File.separator;
if (!destDir.endsWith(File.separator) && !destDir.equals("")) destDir = destDir.concat(File.separator);
try { fileList = getFileList(sourcePaths); connectFTP(); if (_log.isDebugEnabled()) _log.debug("Sending files to remote dir: " + destDir); performPutFiles(fileList, destDir, overwrite);
if (archiveDest) { String remoteArchDir = destDir + archiveDir; if (_log.isDebugEnabled()) _log.debug("remote archive: " + remoteArchDir); performPutFiles(fileList, remoteArchDir, overwrite); }
} catch (FTPConnectionClosedException e) { _log.error("Premature disconnection of server: " + destServer, e); throw new FTPConnectionClosedException("Premature disconnection of server: " + destServer + "\n" + e.getLocalizedMessage()); } catch (IOException e) { _log.error("IO Error on putting files on server:" + destServer, e); throw new IOException("IO Error putting files on server:" + destServer + "\n" + e.getLocalizedMessage()); } catch (Exception e) { throw new Exception("FTP exception " + e); } finally { if (ftp != null) disconnectFTP(); }
// Send files to destination archive if required if (archiveSource) { String aPath = ((File) fileList.get(0)).getPath(); sourceArchDir = (aPath.substring(0, aPath.lastIndexOf(File.pathSeparator) + 1) + archiveDir); performLocalArchive(fileList, sourceArchDir); }
if (cleanup) { performLocalDelete(fileList); } } 待续......
很久以前写的一个FTP的连接代理, 这个代理包含了下载,上传,是否覆盖,是否删除源文件,是否把源文件打包,是否打包目标文件等功能,挺全的。网上例子也挺多的,你参考一下吧。代码有点多,里面自定义的Exception类就不贴出来了package com.dc.test.ftp;import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;import org.apache.commons.net.DefaultSocketFactory;/**
*
*/
public class VpcSocketFactory extends DefaultSocketFactory
{
private int connectTimeout = 0;
public VpcSocketFactory()
{
super();
}
public Socket createSocket(String host, int port)
throws UnknownHostException, IOException
{
Socket socket = new java.net.Socket();
java.net.InetSocketAddress addr = new java.net.InetSocketAddress(host, port);
socket.connect(addr, connectTimeout);
return socket;
} public int getConnectTimeout()
{
return connectTimeout;
} public void setConnectTimeout(int timeout)
{
connectTimeout = timeout;
}
}
package com.dc.test.ftp;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;import java.net.SocketException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;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.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.PropertyConfigurator;public class FtpAgent {
private static final Log _log = LogFactory.getLog(FtpAgent.class);
private final static char LOCAL_ARCHIVE = 1;
private final static char REMOTE_ARCHIVE = 2;
private final long WAIT = 10000;
private FTPClient ftp;
public String server;
public String user;
public String password;
public static void main(String[] args) {
FtpAgent ftpAgent = new FtpAgent();
PropertyConfigurator.configure("./log4j.properties");
String operation = null, server = null, username = null, password = null, source = null, dest = null;
boolean archiveSource = false , archiveDest = false, overwrite = true;
if (args.length == 14) {
for(int i=0; i<args.length; i=i+2) {
if(args[i].equals("-o") || args[i].equals("-O")) operation = args[i+1];
else if(args[i].equals("-v") || args[i].equals("-v")) server = args[i+1];
else if(args[i].equals("-u") || args[i].equals("-U")) username = args[i+1];
else if(args[i].equals("-p") || args[i].equals("-P")) password = args[i+1];
else if(args[i].equals("-s") || args[i].equals("-S")) source = args[i+1];
else if(args[i].equals("-d") || args[i].equals("-D")) dest = args[i+1];
else if(args[i].equals("-a") || args[i].equals("-A")) {
if (args[i+1].equals("s") || args[i].equals("S")) {
archiveSource = true;
archiveDest = false;
} else if (args[i+1].equals("d") || args[i].equals("D")) {
archiveSource = false;
archiveDest = true;
} else if (args[i+1].equals("b") || args[i].equals("B")) {
archiveSource = true;
archiveDest = true;
}
}
}
if (operation.equals("g") || operation.equals("G")) {
try {
ftpAgent.getFiles(server, username, password, source, archiveSource, dest, archiveDest);
System.out.println("Files Transferred Successfully");
System.exit(0);
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
} else if (operation.equals("p") || operation.equals("P")) {
try {
ftpAgent.putFiles(server, username, password, source, archiveSource, true, dest, archiveDest, overwrite);
System.out.println("Files Transferred Successfully");
System.exit(0);
} catch (Exception e){
System.err.println(e);
System.exit(1);
}
}
} else if(args.length == 7) {
if (args[6].equals("s") || args[6].equals("S")) {
archiveSource = true;
archiveDest = false;
} else if (args[6].equals("d") || args[6].equals("D")) {
archiveSource = false;
archiveDest = true;
} else if (args[6].equals("b") || args[6].equals("B")) {
archiveSource = true;
archiveDest = true;
}
if (args[0].equals("g") || args[0].equals("G") || args[0].equals("getFiles")) {
try {
ftpAgent.getFiles(args[1], args[2], args[3], args[4], archiveSource, args[5], archiveDest);
System.out.println("Files Transferred Successfully");
System.exit(0);
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
} else if (args[0].equals("p") || args[0].equals("P") || args[0].equals("putFiles")) {
try {
ftpAgent.putFiles(args[1], args[2], args[3], args[4], archiveSource, true, args[5], archiveDest, overwrite);
System.out.println("Files Transferred Successfully");
System.exit(0);
} catch (Exception e){
System.err.println(e);
System.exit(1);
}
}
} else {
System.err.println("\nInvalid arguments.");
}
System.out.println("NOTE: Source files will be deleted after successful transfer!");
System.out.println("Use archiving function to retain a copy of files");
System.out.println("\nUsage : java -jar ftpAgent.jar ATTRIBUTES");
System.out.println("Example: java -jar ftpAgent.jar -o p -v 192.168.0.1 -u user -p myPassword -s ./source -d ./dest -a s");
System.out.println("\nAttribute = PREFIX ARGUMENT");
System.out.println("Prefixes \t\tArguments");
System.out.println("-o --operation\t\t g|p type of operation: g to get files from server or p to put files on server");
System.out.println("-v --ftp server\t\t server address");
System.out.println("-u --ftp user\t\t ftp account user name");
System.out.println("-p --password\t\t ftp account password");
System.out.println("-s --source\t\t source directory");
System.out.println("-d --destination\t destination directory");
System.out.println("-a --achiving options\t n|s|d|b n-no archiving, s-archive source, d-archive destination, b-both");
System.out.println("\nAlternative: java -jar ftpAgent.jar OPERATION SERVER USER PASSWORD SOURCE_DIRECTORY DESTINATION_DIRECTORY ARCHIVING");
System.out.println("Example: java -jar ftpAgent.jar p 192.168.0.1 user myPassword ./source ./dest s");
}
/*
* get files from sourceDir in the source ftp server using username and password
* and store in destDir. If sourceArchive and or destArchive are given then a copy
* of downloaded files are archived in the respective directories
*
*/
public FtpAgent() {
ftp = new FTPClient();
}
待续......
public void getFiles(String sourceServer, String userName, String pw,
String sourceDir, boolean archiveSource,
String destDir, boolean archiveDest)
throws InvalidFTPServerException, InvalidFTPAccountException, ArchiveException, IOException, Exception{
server = sourceServer;
user = userName;
password = pw;
List recvFiles = null;
File dir = null;
String destArchDir = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
String archiveDir = dFormat.format(cal.getTime()) + File.separator;
if (!sourceDir.endsWith(File.separator) && !sourceDir.equals("")) sourceDir = sourceDir.concat(File.separator);
if (!destDir.endsWith(File.separator) && !destDir.equals("")) destDir = destDir.concat(File.separator);
dir = new File(destDir);
if (!dir.exists()) {
dir.mkdir();
}
try
{
connectFTP();
recvFiles = performGetFromDir(sourceDir, destDir, archiveSource, archiveDir);
if (_log.isDebugEnabled()) _log.debug("Received files : " + recvFiles);
} catch (FTPConnectionClosedException e) {
_log.error("Premature disconnection of server: " + sourceServer, e);
throw new FTPConnectionClosedException("Premature disconnection of server: " + sourceServer + "\n" + e.getLocalizedMessage());
} catch (IOException e) {
_log.error("IO Error on getting files from server:" + sourceServer, e);
throw new IOException("IO Error on getting files from server:" + sourceServer + "\n" + e.getLocalizedMessage() );
} finally {
if (ftp != null) disconnectFTP();
}
// Copy downloaded files to destination archive if required
if (archiveDest) {
destArchDir = destDir + archiveDir;
if (_log.isDebugEnabled()) _log.debug("remote archive: " + destArchDir);
performLocalArchive(recvFiles, destArchDir);
}
}
public void getFiles(String sourceServer, String userName, String pw,
List pathList, boolean archiveSource,
String destDir, boolean archiveDest)
throws InvalidFTPServerException, InvalidFTPAccountException, ArchiveException, IOException, Exception{
server = sourceServer;
user = userName;
password = pw;
List recvFiles = null;
File dir = null;
String destArchDir = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
String archiveDir = dFormat.format(cal.getTime()) + File.separator;
if (!destDir.endsWith(File.separator) && !destDir.equals("")) destDir = destDir.concat(File.separator);
dir = new File(destDir);
if (!dir.exists()) {
dir.mkdir();
}
try
{
connectFTP();
recvFiles = performGetFiles(pathList, destDir, archiveSource, archiveDir);
} catch (FTPConnectionClosedException e) {
_log.error("Premature disconnection of server: " + sourceServer, e);
throw new FTPConnectionClosedException("Premature disconnection of server: " + sourceServer + "\n" + e);
} catch (IOException e) {
_log.error("IO Error on getting files from server:" + sourceServer, e);
throw new IOException("IO Error on getting files from server:" + sourceServer + "\n" + e);
} finally {
if (ftp != null) disconnectFTP();
}
// Copy downloaded files to destination archive if required
if (archiveDest) {
destArchDir = destDir + archiveDir;
if (_log.isDebugEnabled()) _log.debug("remote archive: " + destArchDir);
performLocalArchive(recvFiles, File.separator + destArchDir);
}
}
/*
* takes a directory and put files in the directory in destination directory
*/
public void putFiles(String destServer, String userName, String pw,
String sourceDir, boolean archiveSource, boolean cleanup,
String destDir, boolean archiveDest, boolean overwrite)
throws InvalidFTPServerException, InvalidFTPAccountException, ArchiveException, IOException, SocketException, Exception {
server = destServer;
user = userName;
password = pw;
// list of file objects
List fileList = null;
fileList = getFileList(sourceDir);
Calendar cal = new GregorianCalendar();
SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
String archiveDir = dFormat.format(cal.getTime()) + File.separator;
if (!sourceDir.endsWith(File.separator) && !sourceDir.equals("")) sourceDir = sourceDir.concat(File.separator);
if (!destDir.endsWith(File.separator) && !destDir.equals("")) destDir = destDir.concat(File.separator);
try
{
connectFTP();
performPutFiles(fileList, destDir, overwrite);
if (archiveDest) {
String remoteArchDir = destDir + archiveDir;
if (_log.isDebugEnabled()) _log.debug("remote archive: " + remoteArchDir);
performPutFiles(fileList, remoteArchDir, overwrite);
}
} catch (FTPConnectionClosedException e) {
_log.error("Premature disconnection of server: " + destServer, e);
throw new FTPConnectionClosedException("Premature disconnection of server: " + destServer + "\n" + e.getLocalizedMessage());
} catch (IOException e) {
_log.error("IO Error on putting files on server:" + destServer, e);
throw new IOException("IO Error putting files on server:" + destServer + "\n" + e.getLocalizedMessage());
} finally {
if (ftp != null) disconnectFTP();
}
// Copy downloaded files to source archive if required
if (archiveSource) {
String sourceArchDir = sourceDir + archiveDir;
performLocalArchive(fileList, sourceArchDir);
}
if (cleanup) {
performLocalDelete(fileList);
}
}
/*
* Takes a list of file paths and puts them on remote ftp server
*/
public void putFiles(String destServer, String userName, String pw,
List sourcePaths, boolean archiveSource, boolean cleanup,
String destDir, boolean archiveDest, boolean overwrite)
throws InvalidFTPServerException, InvalidFTPAccountException,
InvalidFileException,ArchiveException,IOException, SocketException, Exception {
server = destServer;
user = userName;
password = pw;
List fileList = new ArrayList();
String sourceArchDir = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
String archiveDir = dFormat.format(cal.getTime()) + File.separator;
if (!destDir.endsWith(File.separator) && !destDir.equals("")) destDir = destDir.concat(File.separator);
try
{
fileList = getFileList(sourcePaths);
connectFTP();
if (_log.isDebugEnabled()) _log.debug("Sending files to remote dir: " + destDir);
performPutFiles(fileList, destDir, overwrite);
if (archiveDest) {
String remoteArchDir = destDir + archiveDir;
if (_log.isDebugEnabled()) _log.debug("remote archive: " + remoteArchDir);
performPutFiles(fileList, remoteArchDir, overwrite);
}
} catch (FTPConnectionClosedException e) {
_log.error("Premature disconnection of server: " + destServer, e);
throw new FTPConnectionClosedException("Premature disconnection of server: " + destServer + "\n" + e.getLocalizedMessage());
} catch (IOException e) {
_log.error("IO Error on putting files on server:" + destServer, e);
throw new IOException("IO Error putting files on server:" + destServer + "\n" + e.getLocalizedMessage());
} catch (Exception e) {
throw new Exception("FTP exception " + e);
}
finally {
if (ftp != null) disconnectFTP();
}
// Send files to destination archive if required
if (archiveSource) {
String aPath = ((File) fileList.get(0)).getPath();
sourceArchDir = (aPath.substring(0, aPath.lastIndexOf(File.pathSeparator) + 1) + archiveDir);
performLocalArchive(fileList, sourceArchDir);
}
if (cleanup) {
performLocalDelete(fileList);
}
}
待续......