ftp服务器的文件夹递归上传与下载

来源:互联网 发布:ackerman函数递归算法 编辑:程序博客网 时间:2024/05/19 02:44
做项目的时候碰到了自己花了点儿时间查资料写了一下,方便以后直接使用
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPFile;import org.apache.commons.net.ftp.FTPReply;import com.frame.tools.PropertiesTools;/** *  * 文件上传下载到FTP服务器 *  */public class FtpUtil {private static FTPClient ftp;private static String localPath="D:\\ftpdownload";static {PropertiesTools propertiesTools = new PropertiesTools();String address = propertiesTools.getProperties("ftpAdress");int port = Integer.parseInt(propertiesTools.getProperties("ftpPort"));String username = propertiesTools.getProperties("ftpUsername");String password = propertiesTools.getProperties("ftpPassword");ftp = new FTPClient();int reply;try {ftp.connect("192.168.12.144", 21);ftp.login("user", "123");ftp.setFileType(FTPClient.BINARY_FILE_TYPE);reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();}} catch (Exception e) {e.printStackTrace();}}/** *  * @param file *            上传的文件或文件夹 * @throws Exception */public static void upload(File file) throws Exception {if (file.isDirectory()) {ftp.makeDirectory(file.getName());ftp.changeWorkingDirectory(file.getName());String[] files = file.list();for (int i = 0; i < files.length; i++) {File file1 = new File(file.getPath() + "\\" + files[i]);if (file1.isDirectory()) {upload(file1);ftp.changeToParentDirectory();} else {File file2 = new File(file.getPath() + "\\" + files[i]);FileInputStream input = new FileInputStream(file2);ftp.storeFile(file2.getName(), input);input.close();}}} else {File file2 = new File(file.getPath());FileInputStream input = new FileInputStream(file2);ftp.storeFile(file2.getName(), input);input.close();}}/** *  * @param path 需要下载的文件或文件夹路径(如:\\test 表示ftp根目录的test文件夹) * @throws Exception */public static void download(String path) throws Exception {FileOutputStream fos =null;File dir = new File(localPath+"\\"+path);if (!dir.exists() && !dir.isDirectory()) {dir.mkdirs();}FTPFile[] files = ftp.listFiles(path);for (int i = 0; i < files.length; i++) {if (files[i].isDirectory()) {File file1 = new File(localPath+"\\" +path+"\\"+ files[i].getName());if (!file1.exists() && !file1.isDirectory()) {file1.mkdirs();}download(path+"\\" + files[i].getName());} else {System.out.println(localPath+"\\"+path+"\\"+files[i].getName());File file2 = new File(localPath+"\\"+path+"\\"+files[i].getName());fos = new FileOutputStream(file2);ftp.retrieveFile(path+"\\"+files[i].getName(), fos);fos.close();}}}public static void main(String[] args) throws Exception {download("//");}}

1 0