模拟FTP功能操作远程服务器上的文件,java有多种处理方式:
1. 采用FTP协议,通过apache的FTPClient。
2. 采用SFTP协议,通过ChannelSftp。
3. 采用SSH协议,通过SCPClient,也就是本文所采用的的方式。
1. 导入FTP相关依赖
<dependency>
<groupId>ch.ethz.ganymedgroupId>
<artifactId>ganymed-ssh2artifactId>
<version>262version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
dependency>
2. 连接远程服务器
public static Connection login(String host, String user, String password) {
Connection conn = new Connection(host);
try {
conn.connect();
boolean b = conn.authenticateWithPassword(user, password);
if (b) {
return conn;
}
} catch (IOException e) {
System.err.printf("用户%s密码%s登录服务器%s失败!", user, password, host);
e.printStackTrace();
}
return null;
}
3. 获取FTP文件流
public static InputStream copyFile2(Connection conn, String fileName) {
SCPClient sc = new SCPClient(conn);
try {
return sc.get(fileName);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
4. 递归获取路径下的所有文件属性
public static TreeNodeDTO getFileProperties(Connection conn, String path) {
try {
SFTPv3Client sft = new SFTPv3Client(conn);
TreeNodeDTO rootNode = new TreeNodeDTO();
dfsFiles(sft, rootNode, path);
sft.close();
return rootNode;
} catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
public static void dfsFiles(SFTPv3Client sft, TreeNodeDTO rootNode, String path) {
List<SFTPv3DirectoryEntry> v = null;
try {
v = sft.ls(path);
if (null == v || v.size() == 0) {
return;
}
} catch (IOException e) {
e.printStackTrace();
}
List<TreeNodeDTO> list = new ArrayList<>();
for (int i = 0; i < v.size(); i++) {
SFTPv3DirectoryEntry s = v.get(i);
SFTPv3FileAttributes attr = s.attributes;\
if (attr.isDirectory() && (s.filename.equals(".") || s.filename.equals(".."))) {
continue;
}
TreeNodeDTO nodeDTO = new TreeNodeDTO();
nodeDTO.setFilename(s.filename);
nodeDTO.setSize(FileUtils.convertSize(attr.size));
nodeDTO.setIsDirectory(attr.isDirectory());
Date createTime = new Date(attr.atime * 1000L);
Date modifyTime = new Date(attr.mtime * 1000L);
nodeDTO.setCreateTime(createTime);
nodeDTO.setModifyTime(modifyTime);
if (attr.isDirectory()) {
dfsFiles(sft, nodeDTO, path + "/" + s.filename);
}
list.add(nodeDTO);
}
rootNode.setChildren(list);
}
5. TreeNode 实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TreeNodeDTO implements Serializable {
private String filename;
private String path;
private String size;
private Boolean isDirectory;
private Date createTime;
private Date modifyTime;
private List<TreeNodeDTO> children = new ArrayList<>();
}
测试
public static void main(String[] args) {
Connection conn = FtpUtils.login("192.168.0.23", "root", "123456");
TreeNodeDTO fileProperties = FtpUtils.getFileProperties(conn, "/data/doodle");
System.out.println(fileProperties);
System.out.println("=============================================");
FtpUtils.copyFile(conn, "/data/doodle/1.txt");
}