FTPUtil

版权声明:本文为博主原创文章,转载请标明来源http://blog.csdn.net/srk950606 宋荣凯的博客 https://blog.csdn.net/srk950606/article/details/79954721
mport java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


import com.clipperadvisor.utils.code.ImpDataCode;
import com.clipperadvisor.utils.exception.ImpDataException;


public class FtpUtil {
	FTPClient ftpClient = null;
	public FtpUtil(String url, int port, String username, String password) throws SocketException, IOException {
		try {
			if (ftpClient != null && ftpClient.isConnected()) {
				return;
			}
			ftpClient = new FTPClient();
			ftpClient.connect(url, port);
			ftpClient.login(username, password);
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				throw new ImpDataException(ImpDataCode.code_1020);
			}
		} catch (Exception e) {
			throw new ImpDataException(ImpDataCode.code_1021);
		}
	}
	
	public File downloadFile(String ftpFilePath, String fileName) throws IOException {
			if (ftpClient.changeWorkingDirectory(ftpFilePath)) {
				FTPFile[] ftpFiles = ftpClient.listFiles();
				for (FTPFile ftpFile : ftpFiles) {
					if (ftpFile.getName().equals(fileName)) {
						File localFile = new File(fileName);
						OutputStream outputStream = new FileOutputStream(localFile);
						ftpClient.retrieveFile(ftpFile.getName(), outputStream);
						outputStream.close();
						return localFile;
					}
				}
			}
			else{
				ftpClient.logout();
				throw new ImpDataException(ImpDataCode.code_1019);
			}
			ftpClient.logout();
			return null;
	}
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页