Skip to content

Instantly share code, notes, and snippets.

@qlong8807
Created April 27, 2018 07:37
Show Gist options
  • Save qlong8807/7c2393278abfbcfee85ec041f82ed838 to your computer and use it in GitHub Desktop.
Save qlong8807/7c2393278abfbcfee85ec041f82ed838 to your computer and use it in GitHub Desktop.
实现FTP下载和FTP备份
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
public class MyFtpUtil {
private static final Logger log = Logger.getLogger(MyFtpUtil.class);
private static String SERVER_NAME = "cos94";
private static final int SERVER_PORT = 21;
private static String LOGIN_NAME = "ftpuser";
private static String LOGIN_PASSWD = "f1";
private static String LOCAL_PATH = "/Users/apple/Documents/test/down";//本地下载目录
private static String REMOTE_PATH = "download";// 下载文件的目录
private static String MOVE_PATH = "downbak";//文件下载后备份的目录
private static String ftpBaseDir;
private static FTPClient ftpClient = new FTPClient();
public static void main(String[] args) throws Exception {
getConnection();
// initPath("hello/downfileabc/down");
// ftpClient.changeWorkingDirectory("hello");
ftpBaseDir = ftpClient.printWorkingDirectory();
// initPath("../hello1/downfileabc/down");
// System.out.println(ftpClient.rename("abc.txt", "hello/ab.txt"));
downloadAll(REMOTE_PATH, LOCAL_PATH, true, MOVE_PATH);
// System.out.println("/a/b/c//d".replaceAll("//", "/"));
disConnection();
}
// 删除全部文件
private static void downloadAll(String remotePath, String localPath, boolean moveFile, String movePath) {
try {
FTPFile[] files = null;
boolean changedir = ftpClient.changeWorkingDirectory(remotePath);
if (changedir) {
files = ftpClient.listFiles();
for (FTPFile file : files) {
downloadFile(file, localPath, remotePath, true, movePath);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
/**
* 下载文件
*/
public static void downloadFile(FTPFile ftpFile, String relativeLocalPath, String relativeRemotePath,
boolean moveFile, String movePath) {
if (ftpFile.isFile()) {// down file
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(relativeLocalPath + "/" + ftpFile.getName());
log.info("download fileName: " + ftpFile.getName());
ftpClient.retrieveFile(ftpFile.getName(), outputStream);
outputStream.flush();
outputStream.close();
// 移动文件
if (moveFile) {
initPath(relativeRemotePath, movePath);
String bakFile = getMutilParent(relativeRemotePath) + movePath + "/" + ftpFile.getName();
boolean rename = ftpClient.rename(ftpFile.getName(), bakFile);
System.err.println("从当前目录:" + ftpClient.printWorkingDirectory() + "移动文件:" + ftpFile.getName()
+ ",到目录:" + bakFile + ",结果:" + rename);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
System.out.println("ShowasaFile");
}
}
} else {
String newlocalRelatePath = relativeLocalPath + '/' + ftpFile.getName();
String newRemote = new String(relativeRemotePath + '/' + ftpFile.getName().toString());
File fl = new File(newlocalRelatePath);
if (!fl.exists()) {
fl.mkdirs();
}
try {
newlocalRelatePath = newlocalRelatePath + '/';
newRemote = newRemote + "/";
String currentWorkDir = ftpFile.getName().toString();
// enter relative workdirectory
boolean changedir = ftpClient.changeWorkingDirectory(currentWorkDir);
if (changedir) {
FTPFile[] files = null;
files = ftpClient.listFiles();
for (int i = 0; i < files.length; i++) {
downloadFile(files[i], newlocalRelatePath, newRemote, moveFile,
movePath + "/" + ftpFile.getName().toString());
}
}
if (changedir)
ftpClient.changeToParentDirectory();
System.out.println("当前目录:"+ftpClient.printWorkingDirectory()+",将要删除目录:"+currentWorkDir);
// 目录下的文件遍历完,删除该目录。
ftpClient.removeDirectory(currentWorkDir);
} catch (Exception e) {
System.out.println(e);
}
}
}
/**
* 创建多级目录,创建完成后返回原目录 当前FTP工作在workDir,创建targetDir后,让FTP还工作在workDir
* 例如:path1、path1/path2、path1/path2/
*
* @param workDir
* 当前工作的路径,FTP根目录的相对路径
* @param targetDir
* 需创建(存在则不创建,不存在则创建)的路径,FTP根目录的相对路径
*/
public static void initPath(String workDir, String targetDir) {
if (null == targetDir || targetDir.isEmpty())
return;
try {
String currDir = ftpClient.printWorkingDirectory();
workDir = formatDir(workDir);
String longWorkDir = ftpBaseDir + "/" + workDir;
// longWorkDir = formatDir(longWorkDir);
if (currDir.equals(longWorkDir)) {
gotoBasePath(workDir);
System.out.println("当前目录:" + ftpClient.printWorkingDirectory());
String[] arr = targetDir.trim().split("/");
if (!ftpClient.changeWorkingDirectory(targetDir)) {
String currentDir = "";
for (String s : arr) {
currentDir = s + "/";
if (ftpClient.changeWorkingDirectory(currentDir))
continue;
if (ftpClient.makeDirectory(currentDir)) {
ftpClient.changeWorkingDirectory(currentDir);
System.err.println("创建目录成功:" + currentDir);
} else {
System.err.println("创建目录失败:" + currentDir);
}
System.out.println("当前目录:" + ftpClient.printWorkingDirectory());
}
}
// 创建完成返回原目录
for (String s : arr) {
ftpClient.changeToParentDirectory();
}
ftpClient.changeWorkingDirectory(workDir);
} else {
System.err.println("目录不匹配,ftp目录:" + currDir + ",工作目录:" + workDir);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String formatDir(String dir) {
dir = dir.trim().replaceAll("//", "/");
if ("/".equals(dir.substring(dir.length() - 1)))
dir = dir.substring(0, dir.length() - 1);
return dir;
}
public static String getMutilParent(String dir) {
dir = formatDir(dir);
String[] split = dir.split("/");
String result = "";
for (String s : split) {
result = result + "../";
}
return result;
}
/**
* 返回FTP根目录
*
* @param workDir
* FTP工作目录,是相对目录,前面不能有/,最后的/可有可无
* @throws IOException
*/
public static void gotoBasePath(String workDir) throws IOException {
String[] split = workDir.trim().split("/");
for (String s : split) {
ftpClient.changeToParentDirectory();
}
}
/**
* 断开连接
*
* @throws Exception
*/
public static void disConnection() throws Exception {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
/**
* 建立连接
*/
public static void getConnection() {
try {
// 解决中文乱码问题
ftpClient.setControlEncoding("utf-8");
ftpClient.connect(SERVER_NAME, SERVER_PORT);
ftpClient.login(LOGIN_NAME, LOGIN_PASSWD);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment