package com.primeton.damp.fileclient; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; /** * * 本地文件系统 模拟 X11 * *
* * Created by zhaopx. * User: zhaopx * Date: 2021/3/31 * Time: 09:38 * ** * @author zhaopx */ public class LocalFsClientHandler implements X11ClientHandler { protected static Logger logger = LoggerFactory.getLogger("LocalFsClientHandler"); /** * 执行路径的基础路径 */ private final String basePath; /** * 本地文件系统 */ private final static FileSystem fs = FileSystems.getDefault(); public LocalFsClientHandler(String basePath) { this.basePath = basePath; } @Override public void reconnect(Properties params) throws IOException { } @Override public OutputStream writeFile(String file, boolean overwrite) throws IOException { final Path fsPath = fs.getPath(basePath, file); return new FileOutputStream(fsPath.toFile(), !overwrite); } @Override public InputStream readFile(String file) throws IOException { return Files.newInputStream(fs.getPath(basePath, file)); } @Override public boolean rename(String file, String newFileName) { try { Path path1 = fs.getPath(file); Path path = fs.getPath(path1.getParent().toString(), newFileName); Files.move(path1, path); logger.info("rename {} to {}", path1.toString(), path.toString()); return true; } catch (Exception e) { logger.error("Error in rename ftp file.", e); return false; } } @Override public boolean deleteFile(String path) { final Path fsPath = fs.getPath(basePath, path); try { if (Files.exists(fsPath) && Files.isDirectory(fsPath)) { // 删除文件夹,连带文件夹一起删除,包括其下的子文件 FileUtils.deleteDirectory(fsPath.toFile()); } else { // 删除文件 Files.delete(fsPath); } } catch (Exception e) { throw new RuntimeException(e); } return true; } @Override public boolean mkdir(String path) { final Path fsPath = fs.getPath(basePath, path); try { Files.createDirectory(fsPath); return existsDir(path); } catch (IOException e) { throw new RuntimeException(e); } } @Override public boolean mkdirs(String path) { final Path fsPath = fs.getPath(basePath, path); return fsPath.toFile().mkdirs(); } @Override public List