package com.primeton.damp.fileclient; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; /** * Created by hadoop on 2018/8/9. */ public class FtpClientHandler implements X11ClientHandler { protected static Logger logger = LoggerFactory.getLogger("FtpClientHandler"); private FTPClient ftpClient; private int reply; private final String ftpHost; private final int ftpPort; private final String ftpUsername; private final String ftpPassword; public FtpClientHandler(String host, int port, String username, String password, Properties params) { ftpHost = host; ftpPort = port; ftpUsername = username; ftpPassword = password; this.reconnect(params); } /** * 以账号和密码重新连接 * @param params */ public void reconnect(Properties params) { try { ftpClient = new FTPClient(); ftpClient.connect(ftpHost, ftpPort); //连接Ftp服务器 ftpClient.login(ftpUsername, ftpPassword); ftpClient.setControlEncoding("UTF-8"); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); // 被动模式 reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { logger.info("Donot connect FTP Server, username or password is error."); ftpClient.disconnect(); } else { logger.info("The FTP connect success."); } } catch (IOException e) { logger.error("ftp connect is error.", e); throw new IllegalStateException("can not connect sftp: " + ftpHost+":"+ ftpPort); } } /** * 读取文件流 * @param file * @return * @throws IOException */ public InputStream readFile(String file) throws IOException { return ftpClient.retrieveFileStream(file); } /** * 读取文件流 * @param file * @return * @throws IOException */ @Override public OutputStream writeFile(String file, boolean overwrite) throws IOException { if(overwrite) { return ftpClient.storeFileStream(file); } else { return ftpClient.appendFileStream(file); } } public boolean renameFile(String file, String newFileName) { try { return ftpClient.rename(file, newFileName); } catch (IOException e) { logger.error("Error in rename ftp file.", e); return false; } } /** * 删除文件, 返回 true 则删除成功 * @param fileName */ public boolean deleteFile(String fileName) { try { return ftpClient.deleteFile(fileName); } catch (IOException e) { logger.info("Delete file fail.", e); } return false; } /** * 判断目录是否存在 * @param path * @return */ @Override public boolean existsDir(String path) { try { FTPFile mdtmFile = ftpClient.mlistFile(path); return mdtmFile != null && mdtmFile.isDirectory(); } catch (IOException e) { logger.error(e.getMessage()); } return false; } /** * 判断目录是否存在 * @param path * @return */ @Override public boolean existsFile(String path) { try { FTPFile mdtmFile = ftpClient.mlistFile(path); return mdtmFile != null && mdtmFile.isFile(); } catch (IOException e) { logger.error(e.getMessage()); } return false; } /** * 判断目录或者文件是否存在 * @param path * @return */ @Override public boolean exists(String path) { try { final FTPFile ftpFile = ftpClient.mdtmFile(path); return ftpFile != null && ftpFile.isValid(); } catch (IOException e) { logger.error(e.getMessage()); } return false; } /** * 创建多层目录 * @param path * @return */ @Override public boolean mkdirs(String path) { Path path1 = Paths.get(path); Path parentPath = path1.getParent(); if(existsDir(parentPath.toString())){ return mkdir(path1.toString()); // 创建当前文件夹 } else { if("/".equals(parentPath.toString()) || mkdirs(parentPath.toString())) { // 创建父级目录 return mkdir(path1.toString()); // 创建当前文件夹 } } // 最后创建文件夹肯定是不成功的。 return existsDir(path); } /** * 创建目录, 返回 true 则创建目录成功 * @param dirName 一级或者多级目录 */ @Override public boolean mkdir(String dirName) { try { return ftpClient.makeDirectory(dirName); } catch (IOException e) { logger.info("mkdir " + dirName + " fail.", e); } return false; } /** * 获取一个目录下或者文件的子文件 * @param ftpPath * @return */ @Override public List getChildren(String ftpPath) { try { FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath); List files = Arrays.stream(ftpFiles).map(it->Paths.get(ftpPath, it.getName())).collect(Collectors.toList()); return files; } catch (IOException e) { logger.info("Error in scan ftpfile."); } return Collections.emptyList(); } @Override public void close() throws IOException { ftpClient.disconnect(); } //test public static void main(String[] args) throws IOException { Properties map = new Properties(); String host = "192.168.30.143"; int port = 2121; String username = "admin"; String password = "primeton000000"; FtpClientHandler handler = new FtpClientHandler(host, port, username, password, map); // handler.changeWorkingDirectory("/sms"); List result = handler.getChildren("/DAMP"); for (Path ftpFile : result) { System.out.println(ftpFile.toString()); } /* OutputStream out = handler.writeFile("/hello.txt", false); IOUtils.copy(new FileInputStream("pom.xml"), out); out.flush(); out.close(); */ System.out.println(handler.exists("/")); System.out.println(handler.exists("/hello.txt")); System.out.println(handler.exists("/example_data_1225")); System.out.println(handler.exists("/world/example_data_1225")); if(!handler.existsDir("/world/example_data_1225")) { System.out.println(handler.mkdirs("/world/example_data_1225")); } System.out.println(handler.exists("/world/example_data_1225")); } }