FTP操作文件

FTP工具类,操作ftp连接,上传,下载,删除文件等,都亲测 

package com.jk.modules.interfaces.bizaccount.util.sftp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.jfree.util.Log;

/**
 *  * FTP连接  *   * @author xxx  2015-03-11   
 */
public class FtpClientUtil {
	@Override
	public String toString() {
		return "FtpClientUtil [server=" + server + ", username=" + username + ", password=" + password + ", ftp=" + ftp
				+ ", binaryTransfer=" + binaryTransfer + "]";
	}


	private static String server="192.168.232.145";
	private static String username="ftpuser";
	private static String password="12345678";
	private FTPClient ftp;
	private boolean binaryTransfer = false;

	/**
	 * @param server
	 *                       ftp服务器地址
	 * @param username
	 *                       ftp服务器登陆用户
	 * @param password
	 *                       ftp用户密码
	 */
	public FtpClientUtil(String server, String username, String password) {
		this.server = server;
		this.username = username;
		this.password = password;
		ftp = new FTPClient();
		/*
		 * if(Configuration.PrintFTPCommandLog){ //打印FTP命令
		 * ftp.addProtocolCommandListener(new PrintCommandListener()); }
		 */
	}
	
	public static void main(String[] args){
		System.out.println("123");
		FtpClientUtil t=new FtpClientUtil(server,username,password);
		boolean bb=t.connect();
		System.out.println("连接是否成功---"+bb);
		
		System.out.println("文件便利开始");
		String[] arr=t.listNames("/new");
		for(String str:arr){
			System.out.println(str);
		}
		System.out.println("文件便利结束");
		
		boolean bb1=t.downFileFromRemoteServer("1t.txt", false);
		if(bb1){
			System.out.println("下载文件到本地成功");
		}
		
		
		boolean bb2=t.sendLocalFileToFtpServer("aaa.txt", false, "/new/");
		if(bb2){
			System.out.println("上传文件到服务器成功");
		}
		
		
		//创建某个目录
		try {
			t.makeDirectory("/new/aaa");
			t.makeDirectory("/new/bbb");
			System.out.println("创建目录成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
//		t.deleteFiles("/new");
//		System.out.println("删除目录下所有文件成功");
//		
//		
//		t.deleteFolder("/new/aaa");
//		System.out.println("删除目录成功");
		
		String arrr=t.readFile("/new/aaa.txt");
		System.out.println(" -----------该目录下所有文件的字符串"+arrr);
		
	}

	public boolean connect() {
		try {
			int reply;
			// 设置连接时间
			ftp.setConnectTimeout(Parameter.FTP_TIME_OUT);

			ftp.connect(server);

			// 连接后检测返回码来校验连接是否成功
			reply = ftp.getReplyCode();

			if (FTPReply.isPositiveCompletion(reply)) {
				if (ftp.login(username, password)) {
					// 设置为passive模式
					ftp.enterLocalPassiveMode();
					return true;
				}
			} else {
				ftp.disconnect();
			}
		} catch (IOException e) {
			System.err.println("FTP连接失败");
			e.printStackTrace();
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException f) {
					System.err.println("FTP关闭失败");
					f.printStackTrace();
				}
			}
		}
		return false;
	}

	/**
	 * 下载一个文件到默认的本地路径中  
	 * 
	 * @param fileName
	 *                       文件名称(不含路径)
	 * @param delFile
	 *                       成功后是否删除该文件
	 * @return
	 */
	public boolean downFileFromRemoteServer(String fileName, boolean delFile) {
		String remote = Parameter.FTP_REMOTE_DOWNPATH + fileName;
		String local = Parameter.FTP_LOCAL_DOWNPATH + fileName;
		return get(remote, local, delFile);
	}

	/**
	 * 上传一个文件到默认的远程路径中 提前定义好路径  
	 * 
	 * @param fileName
	 *                       文件名称(不含路径)
	 * @param delFile
	 *                       成功后是否删除该文件
	 * @return
	 */
	public boolean sendLocalFileToFtpServer(String fileName, boolean delFile, String remotePath) {
		String remote = remotePath + fileName;
		String local = Parameter.FTP_LOCAL_UPPATH + fileName;
		
		System.out.println("remote"+remote+"         local"+local);
		return put(remote, local, delFile);
	}



	/**
	 * 上传多个文件到默认的远程路径中  
	 * 
	 * @param fileNames
	 *                       文件名数组
	 * @param delFile
	 *                       成功后是否删除文件
	 * @return
	 */
	public boolean[] put(String[] fileNames, boolean delFile, String remotePath) {
		boolean[] result = new boolean[fileNames.length];
		for (int j = 0; j < result.length; j++) {
			result[j] = false;
		}
		String localFile;
		for (int i = 0; i < fileNames.length; i++) {
			localFile = fileNames[i];
			result[i] = sendLocalFileToFtpServer(localFile, delFile, remotePath);
		}
		return result;
	}

	

	/**
	 * 上传一个本地文件到远程指定文件  
	 * 
	 * @param remoteAbsoluteFile
	 *                       远程文件名(包括完整路径)
	 * @param localAbsoluteFile
	 *                       本地文件名(包括完整路径)
	 * @return 成功时,返回true,失败返回false
	 */
	public boolean put(String remoteAbsoluteFile, String localAbsoluteFile, boolean delFile) {
		InputStream input = null;
		try {
			// //设置文件传输类型
			if (binaryTransfer) {
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			} else {
				ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
			}
			// 处理传输
			input = new FileInputStream(localAbsoluteFile);
			ftp.storeFile(remoteAbsoluteFile, input);
			if (delFile) {
				File oldFile = new File(localAbsoluteFile);
				if (oldFile.isFile() && oldFile.exists()) {
					System.out.println("删除文件:" + localAbsoluteFile);
					oldFile.delete();
				}

				(new File(localAbsoluteFile)).delete();
			}
			return true;
		} catch (FileNotFoundException e) {
			System.err.println("Local file not found:" + e.getMessage());
			e.printStackTrace();
		} catch (IOException e1) {
			System.err.println("Could put file to server.");
			e1.printStackTrace();
		} finally {
			try {
				if (input != null) {
					input.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

		return false;
	}

	/**
	 * 下载一个远程文件到本地的指定文件  
	 * 
	 * @param remoteAbsoluteFile
	 *                       远程文件名(包括完整路径)
	 * @param localAbsoluteFile
	 *                       本地文件名(包括完整路径)
	 * @return 成功时,返回true,失败返回false
	 */
	public boolean get(String remoteAbsoluteFile, String localAbsoluteFile, boolean delFile) {
		OutputStream output = null;
		try {
			// 设置文件传输类型
			if (binaryTransfer) {
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			} else {
				ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
			}
			// 处理传输
			output = new FileOutputStream(localAbsoluteFile);
			ftp.retrieveFile(remoteAbsoluteFile, output);
			output.close();
			if (delFile) { // 删除远程文件
				ftp.deleteFile(remoteAbsoluteFile);
			}
			return true;
		} catch (FileNotFoundException e) {
			System.err.println("Local file not found:" + e.getMessage());
		} catch (IOException e1) {
			System.err.println("Could put file to server.");
			e1.printStackTrace();
		} finally {
			try {
				if (output != null) {
					output.close();
				}
			} catch (IOException e2) {
			}
		}
		return false;
	}

	/**
	 * 列出远程目录下所有的文件  
	 * 
	 * @param remotePath
	 *                       远程目录名
	 * @return 远程目录下所有文件名的列表,目录不存在或者目录下没有文件时返回0长度的数组
	 */
	public String[] listNames(String remotePath) {
		String[] fileNames = null;
		try {
			FTPFile[] remotefiles = ftp.listFiles(remotePath);
			fileNames = new String[remotefiles.length];
			for (int i = 0; i < remotefiles.length; i++) {
				fileNames[i] = remotefiles[i].getName();
			}
		} catch (IOException e) {
			System.err.println("Could put file to server.");
			e.printStackTrace();
		}
		return fileNames;
	}

	public void moveFilesByRename(String oldFilePath, String newFilePath) throws Exception {
		ftp.rename(oldFilePath, newFilePath);
		ftp.deleteFile(oldFilePath);
	}

	/**
	 * 创建文件夹  
	 * 
	 * @param pathName
	 * @throws Exception
	 */
	public void makeDirectory(String pathName) throws Exception {
		ftp.makeDirectory(pathName);
	}

	/**
	 * @param localPath
	 * @param remotePath
	 *                       必须存在
	 * @param delFile
	 */

	// 原方法-xht
	// public void putFolder(String localPath, String remotePath) throws
	// Exception
	// {
	// System.out.println(">>>>>>>>>>>putFolder>>>>>>>>>");
	// System.out.println("localPath:[" + localPath + "]");
	// System.out.println("remotePath:[" + remotePath + "]");
	// //跳转至工作目录
	// ftp.changeWorkingDirectory(remotePath);
	// File parentFolder = new File(localPath);
	// ftp.makeDirectory(parentFolder.getName());
	// String[] files = parentFolder.list();
	// for (int i = 0; i < files.length; i++) {
	// String childPath = parentFolder.getPath()+"/"+files[i];
	// File file = new File(parentFolder.getPath()+"/"+files[i]);
	// if(file.isDirectory()){
	// putFolder(childPath, parentFolder.getName());
	// ftp.changeToParentDirectory();
	// }else{
	// ftp.changeWorkingDirectory(parentFolder.getName());
	// FileInputStream is = new FileInputStream(file);
	// ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
	// ftp.storeFile(file.getName(), is);
	// is.close();
	// }
	// }
	// }

	// 上面为原方法,现在为更改影像目录所做更新-xht
	public void putFolder(String localPath, String remotePath, String applyCode) throws Exception {
		// 跳转至工作目录 如果工作目录为空,刚在此以年月创建。
		if (null == remotePath || "".equals(remotePath)) {
			String path = Parameter.CEBBANK_FTP_LOCAL_UPPATH;
			ftp.changeWorkingDirectory(path);

			String year = applyCode.substring(1, 5);
			String month = applyCode.substring(5, 7);

			ftp.makeDirectory(year);
			ftp.changeWorkingDirectory(year);
			ftp.makeDirectory(month);
			ftp.changeWorkingDirectory(month);
		} else {
			ftp.changeWorkingDirectory(remotePath);
		}
		File parentFolder = new File(localPath);
		ftp.makeDirectory(parentFolder.getName());
		String[] files = parentFolder.list();
		for (int i = 0; i < files.length; i++) {
			String childPath = parentFolder.getPath() + "/" + files[i];
			File file = new File(parentFolder.getPath() + "/" + files[i]);
			if (file.isDirectory()) {
				putFolder(childPath, parentFolder.getName(), applyCode);
				ftp.changeToParentDirectory();
			} else {
				ftp.changeWorkingDirectory(parentFolder.getName());
				FileInputStream is = new FileInputStream(file);
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
				ftp.storeFile(file.getName(), is);
				is.close();
			}
		}
	}

	public void deleteFiles(String path) {
		try {
			if(ftp==null){
				System.out.println("456");
			}
			String[] names = ftp.listNames(path);
			if (names != null && names.length > 0) {
				for (String name : names) {
					if (!ftp.deleteFile(name)) {
						deleteFolder(name);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void deleteFolder(String path) {
		try {
			String[] names = ftp.listNames(path);
			if (names != null && names.length > 0) {
				for (String name : names) {
					if (!ftp.deleteFile(name)) {
						deleteFolder(name);
					}
				}
			}

			ftp.removeDirectory(path);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 断开ftp连接
	 */
	public void disconnect() {
		try {
			ftp.logout();
			if (ftp.isConnected()) {
				ftp.disconnect();
			}
		} catch (IOException e) {
			System.err.println("Could put file to server.");
			e.printStackTrace();
		}
	}

	/**
	 * @return Returns the binaryTransfer.
	 */
	public boolean isBinaryTransfer() {
		return binaryTransfer;
	}

	/**
	 * @param binaryTransfer
	 *                       The binaryTransfer to set.
	 */
	public void setBinaryTransfer(boolean binaryTransfer) {
		this.binaryTransfer = binaryTransfer;
	}

	
	/**
	 * 读取ftp目录下的文件,返回文件字符内容
	 * 
	 * @param remoteFile
	 * @return
	 */
	public String readFile(String remoteFile) {
		String result = "";
		InputStream ins = null;
		try {
			ins = ftp.retrieveFileStream(remoteFile);
			BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
			String line = "";
			StringBuffer sb = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
			reader.close();
			if (ins != null) {
				ins.close();
			}
			ftp.getReply();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public void putFolderNJCB(String localPath, String remotePath, String applyCode) throws Exception {
		// 跳转至工作目录 如果工作目录为空,刚在此以年月创建。
		if (null == remotePath || "".equals(remotePath)) {
			String path = Parameter.NJCBBANK_FTP_LOCAL_UPPATH;
			ftp.changeWorkingDirectory(path);

			String year = applyCode.substring(1, 5);
			String month = applyCode.substring(5, 7);

			ftp.makeDirectory(year);
			ftp.changeWorkingDirectory(year);
			ftp.makeDirectory(month);
			ftp.changeWorkingDirectory(month);
		} else {
			ftp.changeWorkingDirectory(remotePath);
		}
		File parentFolder = new File(localPath);
		ftp.makeDirectory(parentFolder.getName());
		String[] files = parentFolder.list();
		for (int i = 0; i < files.length; i++) {
			String childPath = parentFolder.getPath() + "/" + files[i];
			File file = new File(parentFolder.getPath() + "/" + files[i]);
			if (file.isDirectory()) {
				putFolderNJCB(childPath, parentFolder.getName(), applyCode);
				ftp.changeToParentDirectory();
			} else {
				ftp.changeWorkingDirectory(parentFolder.getName());
				FileInputStream is = new FileInputStream(file);
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
				ftp.storeFile(file.getName(), is);
				is.close();
			}
		}
	}

	

	public String moveFolderForDownload(String localPath, String fileName) throws Exception {
		String applyCode = fileName.substring(2, fileName.lastIndexOf("."));
		ftp.changeWorkingDirectory(localPath);

		String year = applyCode.substring(1, 5);
		String month = applyCode.substring(5, 7);
		String day = applyCode.substring(7, 9);

		ftp.makeDirectory(year);
		ftp.changeWorkingDirectory(year);
		ftp.makeDirectory(month);
		ftp.changeWorkingDirectory(month);
		ftp.makeDirectory(day);
		ftp.changeWorkingDirectory(day);

		String newPath = localPath + year + "/" + month + "/" + day + "/" + fileName;

		return newPath;
	}

}

 

 

里面用到一个类,如下

 

package com.jk.modules.interfaces.bizaccount.util.sftp;

public class Parameter {

	public static final String FTP_REMOTE_DOWNPATH = "/new";
	public static final String FTP_LOCAL_DOWNPATH = "D:\\";
	public static final String FTP_LOCAL_UPPATH = "D:\\";
	public static final String CGBBANK_FTP_LOCAL_UPPATH = null;
	public static final String NJCBBANK_FTP_LOCAL_UPPATH = null;
	public static final int FTP_TIME_OUT = 0;
	public static final String FTP_REMOTE_UPPATH = null;
	public static final String CEBBANK_FTP_LOCAL_UPPATH = null;

}

 

欢迎交流评论

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知乎关注八戒来了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值