package ftp; import com.google.common.collect.Lists; import org.apache.sshd.client.subsystem.sftp.fs.SftpFileSystemProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.nio.file.*; import java.util.*; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; /** * Created by hadoop on 2018/8/9. */ public class SftpClientHandler implements P11ClientHandler { protected static Logger logger = LoggerFactory.getLogger("SftpClientHandler"); private final String sftpHost; private final int sftpPort; private final String ftpUsername; private final String ftpPassword; /** * sftp 文件系统 */ FileSystem fs; public SftpClientHandler(String host, int port, String username, String password, Properties params) { sftpHost = host; sftpPort = port; ftpUsername = username; ftpPassword = password; this.reconnect(params); } /** * 以账号和密码重新连接 * @param params */ @Override public void reconnect(Properties params) { java.net.URI uri = SftpFileSystemProvider.createFileSystemURI(this.sftpHost, sftpPort, ftpUsername, ftpPassword); try { fs = FileSystems.newFileSystem(uri, (Map) params); } catch (FileSystemAlreadyExistsException e){ logger.warn("exists file system sftp..."); fs = FileSystems.getFileSystem(uri); } catch (IOException e) { logger.error("ftp connect is error.", e); throw new IllegalStateException("can not connect sftp: " + sftpHost+":"+ sftpPort); } } /** * 读取文件流 * @param file * @return * @throws IOException */ @Override public OutputStream writeFile(String file, boolean overwrite) throws IOException { Path path1 = fs.getPath(file); if(overwrite) { return Files.newOutputStream(path1, CREATE); } else { return Files.newOutputStream(path1, APPEND); } } public boolean renameFile(String file, String newFileName) { try { Path path1 = fs.getPath(file); Path path = Paths.get(path1.getParent().toString(), newFileName); Files.move(path, path1); return true; } catch (Exception e) { logger.error("Error in rename ftp file.", e); return false; } } /** * 删除文件, 返回 true 则删除成功 * @param path */ public boolean deleteFile(String path) { try { Path path1 = fs.getPath(path); Files.delete(path1); } catch (Exception e) { logger.info("Delete file fail.", e); } return false; } /** * 判断目录是否存在 * @param path * @return */ @Override public boolean existsDir(String path) { try { Path path1 = fs.getPath(path); return Files.exists(path1) && Files.isDirectory(path1); } catch (Exception e) { } return false; } /** * 判断目录是否存在 * @param path * @return */ @Override public boolean existsFile(String path) { try { Path path1 = fs.getPath(path); return Files.exists(path1) && Files.isRegularFile(path1); } catch (Exception e) { } return false; } /** * 判断目录或者文件是否存在 * @param path * @return */ @Override public boolean exists(String path) { try { Path path1 = fs.getPath(path); return Files.exists(path1); } catch (Exception e) { } return false; } /** * 创建多层目录 * @param path * @return */ @Override public boolean mkdirs(String path) { Path path1 = fs.getPath(path); Path parentPath = path1.getParent(); if(parentPath == null) { // parentPath 等于 null 则说明是文件系统的根目录了。 return true; } // 父级目录已经存在,只创建当前目录 if(existsDir(parentPath.toString())){ return mkdir(path1.toString()); // 创建当前文件夹 } else { // 父级目录不存在,则先创建父级目录,再创建当前目录 if(mkdirs(parentPath.toString())) { // 创建父级目录 return mkdir(path1.toString()); // 创建当前文件夹 } } // 最后创建文件夹肯定是不成功的。 return existsDir(path); } /** * 创建目录, 返回 true 则创建目录成功 * @param dirName 一级或者多级目录 */ @Override public boolean mkdir(String dirName) { try { Path path1 = fs.getPath(dirName); Files.createDirectory(path1); return true; } catch (IOException e) { logger.info("mkdir " + dirName + " fail.", e); } return false; } /** * 获取一个目录下或者文件的子文件 * @param ftpPath * @return */ @Override public List getChildren(String ftpPath) { Path remotePath = fs.getPath(ftpPath); try { DirectoryStream paths = Files.newDirectoryStream(remotePath); return Lists.newArrayList(paths.iterator()); } catch (IOException e) { logger.info("Error in scan sftpfile."); } return Collections.emptyList(); } @Override public void close() throws IOException { logger.warn("close the file system"); fs.close(); } public static void main(String[] args) { Properties map = new Properties(); String host = "localhost"; int port = 2121; String username = "admin"; String password = "admin"; SftpClientHandler handler = new SftpClientHandler(host, port, username, password, map); // handler.changeWorkingDirectory("/sms"); List result = handler.getChildren("/"); /* OutputStream out = handler.writeFile("/hello.txt", false); IOUtils.copy(new FileInputStream("pom.xml"), out); out.flush(); out.close(); */ handler.exists("/hello.txt"); handler.exists("/example_data_1225"); handler.exists("/world/example_data_1225"); handler.mkdirs("/world/example_data_1225"); handler.exists("/world/example_data_1225"); } }