- username=admin
- password=123
- ip=192.168.14.117
- port=21
参考:http://blog.csdn.net/yelove1990/article/details/41245039
实现类
- package com.util;
-
- import java.io.*;
- import java.net.SocketException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Properties;
-
- 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.FTPFile;
- import org.apache.commons.net.ftp.FTPReply;
-
- public class FTPClientTest {
-
- private static final Log logger = LogFactory.getLog(FTPClientTest.class);
-
- private String userName;
- private String password;
- private String ip;
- private int port;
- private Properties property = null;
- private String configFile = "conf/application.properties";
- private FTPClient ftpClient = null;
-
- private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
-
- public int i = 1;
-
-
- public boolean connectServer() {
- boolean flag = true;
- if (ftpClient == null) {
- int reply;
- try {
- if(setArg(configFile)){
- ftpClient = new FTPClient();
- ftpClient.setControlEncoding("GBK");
-
- ftpClient.connect(ip,port);
- ftpClient.login(userName, password);
- reply = ftpClient.getReplyCode();
- ftpClient.setDataTimeout(120000);
-
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftpClient.disconnect();
- logger.debug("FTP 服务拒绝连接!");
- flag = false;
- }
- i++;
- }else{
- flag = false;
- }
- } catch (SocketException e) {
- flag = false;
- e.printStackTrace();
- logger.debug("登录ftp服务器 " + ip + " 失败,连接超时!");
- } catch (IOException e) {
- flag = false;
- e.printStackTrace();
- logger.debug("登录ftp服务器 " + ip + " 失败,FTP服务器无法打开!");
- }
- }
- return flag;
- }
-
-
- public boolean uploadFile(String remoteFile, File localFile)
- throws IOException {
- boolean flag = false;
- InputStream in = new FileInputStream(localFile);
- String remote = new String(remoteFile.getBytes("GBK"),"iso-8859-1");
- if(ftpClient.storeFile(remote, in)){
- flag = true;
- logger.debug(localFile.getAbsolutePath()+"上传文件成功!");
- }else{
- logger.debug(localFile.getAbsolutePath()+"上传文件失败!");
- }
- in.close();
- return flag;
- }
-
-
- public boolean uploadFile(String local, String remote) throws IOException {
- boolean flag = true;
- String remoteFileName = remote;
- if (remote.contains("/")) {
- remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
-
- if (!CreateDirecroty(remote)) {
- return false;
- }
- }
- FTPFile[] files = ftpClient.listFiles(new String(remoteFileName));
- File f = new File(local);
- if(!uploadFile(remoteFileName, f)){
- flag = false;
- }
- return flag;
- }
-
-
- public List uploadManyFile(String filename, String uploadpath) {
- boolean flag = true;
- List l = new ArrayList();
- StringBuffer strBuf = new StringBuffer();
- int n = 0;
- int m = 0;
- try {
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- ftpClient.enterLocalPassiveMode();
- ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
- ftpClient.changeWorkingDirectory("/");
- File file = new File(filename);
- File fileList[] = file.listFiles();
- for (File upfile : fileList) {
- if (upfile.isDirectory()) {
- uploadManyFile(upfile.getAbsoluteFile().toString(),uploadpath);
- } else {
- String local = upfile.getCanonicalPath().replaceAll("\\\\","/");
- String remote = uploadpath.replaceAll("\\\\","/") + local.substring(local.indexOf("/") + 1);
- flag = uploadFile(local, remote);
- ftpClient.changeWorkingDirectory("/");
- }
- if (!flag) {
- n++;
- strBuf.append(upfile.getName() + ",");
- logger.debug("文件[" + upfile.getName() + "]上传失败");
- } else{
- m++;
- }
- }
- l.add(0, n);
- l.add(1, m);
- l.add(2, strBuf.toString());
- } catch (NullPointerException e) {
- e.printStackTrace();
- logger.debug("本地文件上传失败!找不到上传文件!", e);
- } catch (Exception e) {
- e.printStackTrace();
- logger.debug("本地文件上传失败!", e);
- }
- return l;
- }
-
-
- public boolean loadFile(String remoteFileName, String localFileName) {
- boolean flag = true;
-
- 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 boolean deleteFile(String filename) {
- boolean flag = true;
- try {
- flag = ftpClient.deleteFile(filename);
- if (flag) {
- logger.debug("删除文件"+filename+"成功!");
- } else {
- logger.debug("删除文件"+filename+"成功!");
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- return flag;
- }
-
-
- public void deleteDirectory(String pathname) {
- try {
- File file = new File(pathname);
- if (file.isDirectory()) {
- File file2[] = file.listFiles();
- } else {
- deleteFile(pathname);
- }
- ftpClient.removeDirectory(pathname);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
-
-
- public void deleteEmptyDirectory(String pathname) {
- try {
- ftpClient.removeDirectory(pathname);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
-
-
- public void listRemoteFiles(String regStr) {
- try {
- String files[] = ftpClient.listNames(regStr);
- if (files == null || files.length == 0)
- logger.debug("没有任何文件!");
- else {
- for (int i = 0; i < files.length; i++) {
- System.out.println(files[i]);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
- public void listRemoteAllFiles() {
- try {
- String[] names = ftpClient.listNames();
- for (int i = 0; i < names.length; i++) {
- System.out.println(names[i]);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
- public void closeConnect() {
- try {
- if (ftpClient != null) {
- ftpClient.logout();
- ftpClient.disconnect();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
- public void setFileType(int fileType) {
- try {
- ftpClient.setFileType(fileType);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
- private boolean setArg(String configFile) {
- boolean flag = true;
- property = new Properties();
- BufferedInputStream inBuff = null;
- try {
- inBuff = new BufferedInputStream(new FileInputStream(getClass().getResource("/").getPath() + configFile));
- property.load(inBuff);
- userName = property.getProperty("username");
- password = property.getProperty("password");
- ip = property.getProperty("ip");
- port = Integer.parseInt(property.getProperty("port"));
- } catch (FileNotFoundException e1) {
- flag = false;
- logger.debug("配置文件 " + configFile + " 不存在!");
- } catch (IOException e) {
- flag = false;
- logger.debug("配置文件 " + configFile + " 无法读取!");
- }
- return flag;
- }
-
-
-
-
- public boolean changeWorkingDirectory(String directory) {
- boolean flag = true;
- try {
- flag = ftpClient.changeWorkingDirectory(directory);
- if (flag) {
- logger.debug("进入文件夹"+ directory + " 成功!");
-
- } else {
- logger.debug("进入文件夹"+ directory + " 失败!");
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- return flag;
- }
-
-
- public void changeToParentDirectory() {
- try {
- ftpClient.changeToParentDirectory();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
-
-
- public void renameFile(String oldFileName, String newFileName) {
- try {
- ftpClient.rename(oldFileName, newFileName);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
-
-
- private FTPClientConfig getFtpConfig() {
- FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
- ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
- return ftpConfig;
- }
-
-
- private String iso8859togbk(Object obj) {
- try {
- if (obj == null)
- return "";
- else
- return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
- } catch (Exception e) {
- return "";
- }
- }
-
-
- public boolean makeDirectory(String dir) {
- boolean flag = true;
- try {
- flag = ftpClient.makeDirectory(dir);
- if (flag) {
- logger.debug("创建文件夹"+ dir + " 成功!");
-
- } else {
- logger.debug("创建文件夹"+ dir + " 失败!");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return flag;
- }
-
-
- public boolean existFile(String path) throws IOException {
- boolean flag = false;
- FTPFile[] ftpFileArr = ftpClient.listFiles(path);
-
- if(ftpFileArr.length > 0){
- flag = true;
- }
- return flag;
- }
-
-
- public boolean CreateDirecroty(String remote) throws IOException {
- boolean success = true;
- String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
-
- if (!directory.equalsIgnoreCase("/")&& !changeWorkingDirectory(new String(directory))) {
- int start = 0;
- int end = 0;
- if (directory.startsWith("/")) {
- start = 1;
- } else {
- start = 0;
- }
- end = directory.indexOf("/", start);
- while (true) {
- String subDirectory = new String(remote.substring(start, end).getBytes("GBK"),"iso-8859-1");
- if (changeWorkingDirectory(subDirectory)) {
- if (makeDirectory(subDirectory)) {
- changeWorkingDirectory(subDirectory);
- } else {
- logger.debug("创建目录["+subDirectory+"]失败");
- System.out.println("创建目录["+subDirectory+"]失败");
- success = false;
- return success;
- }
- }
- start = end + 1;
- end = directory.indexOf("/", start);
-
- if (end <= start) {
- break;
- }
- }
- }
- return success;
- }
-
- public static void main(String[] args) {
- FTPClientTest ftpClient = new FTPClientTest();
- if(ftpClient.connectServer()){
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- ftpClient.uploadManyFile("H:\\d", "/d/");
- ftpClient.closeConnect();
- }
- }
- }
FTP之二
原文:http://www.cnblogs.com/xyzq/p/6825075.html