需求:
在前面一篇文章中http://supercharles888.blog.51cto.com/609344/980322,我们已经介绍了如何创建一个到远程服务器的连接,那么这里我们就介绍如何通过这个连接来从远程服务器删除单个目录。
实现:
同样,所有的操作都是在ch.ethz.ssh2包中,所以我们必须在maven dependency中声明对相应artifact的依赖.
- <!-- charles:this artifact is used for implementing the scp feature -->
- <dependency>
- <groupId>ch.ethz.ganymed</groupId>
- <artifactId>ganymed-ssh2</artifactId>
- <version>build210</version>
- </dependency>
从远程服务器指定目录删除单个目录的实现,贴上代码:
- /**
- * This method can do the remote delete a folder feature from the web server
- * @param folderPath the folder path which relative to the "htdocs" folder of the web server directory
- * @throws Exception
- */
- public void deleteFolderFromWebServer(String folderPath) throws Exception {
- // check the folderPath shouldn't be null
- if ((folderPath == null) || (folderPath.trim().equals(EMPTY_STRING))) {
- if (logger.isErrorEnabled()) {
- logger.error("the folder path that we want to delete from remote web server shouldn't be null");
- }
- throw new ParameterNullException(
- "the folder path that we want to delete from remote web server shouldn't be null");
- }
- if (logger.isDebugEnabled()) {
- logger.debug("Begin to delete the folder " + folderPath
- + " from WebServer: " + connFactory.getWebServerName());
- }
- // get the connection object
- Connection conn = connFactory.getServerMachineConnection();
- if (conn == null) {
- if (logger.isErrorEnabled()) {
- logger.error("Failed to establish the valid connection with web server "
- + connFactory.getWebServerName());
- }
- throw new DeleteFromWebServerException(
- "Failed to establish the valid connection with web server "+ connFactory.getWebServerName());
- }
- SFTPv3Client client = new SFTPv3Client(conn);
- // use the sftp client to remote delete the folder
- try {
- sftpDeleteFolderRecursive(client,webServerRoot + FORWARD_SLASH +folderPath);
- } catch (IOException ex) {
- if (logger.isErrorEnabled()) {
- logger.error("IOException occured during remote delete folder from "+connFactory.getWebServerName());
- }
- conn.close();
- throw new DeleteFromWebServerException(
- "IOException occured during remote delete folder from "+connFactory.getWebServerName(),ex);
- }
- if (logger.isDebugEnabled()) {
- logger.debug("remote delete folder from web server: " + webServerRoot + " successful");
- }
- // close the connection to web server
- conn.close();
- }
- private List<SFTPv3DirectoryEntry> sftpGetFileList(SFTPv3Client client, String directory) throws Exception
- {
- List<SFTPv3DirectoryEntry> fileEntries = new ArrayList<SFTPv3DirectoryEntry>();
- Vector<?> files = client.ls(directory);
- for (Iterator<?> elements = files.iterator() ; elements.hasNext() ; ) {
- SFTPv3DirectoryEntry file = (SFTPv3DirectoryEntry) elements.next();
- String fileName = file.filename.trim();
- if(!fileName.equals(".") && !fileName.equals(".."))
- fileEntries.add(file);
- }
- return fileEntries;
- }
- /**
- * This method can do the sftp delete a folder recursively feature from the web server
- * @param folderPath the folder path which relative to the "htdocs" folder of the web server directory
- * @throws Exception
- */
- private void sftpDeleteFolderRecursive(SFTPv3Client client,String folderPath) throws Exception {
- List<SFTPv3DirectoryEntry> files = sftpGetFileList(client,folderPath);
- for(SFTPv3DirectoryEntry file : files)
- {
- String fileName = file.filename;
- if(".".equals(fileName.trim()) == false && "..".equals(fileName.trim()) == false)
- {
- //if the file object is a directory,then recursively invokes this method
- if (file.attributes.isDirectory())
- {
- sftpDeleteFolderRecursive(client, folderPath + "/" + fileName);
- } else
- //if the file object is a file ,then just client.rm to sftp delete this file
- {
- client.rm(folderPath + "/" + fileName);
- }
- }
- }
- client.rmdir(folderPath);
- }
这个功能点也比较复杂, 因为没有默认的API提供,我们所能用的只是删除单个文件,所以对于删除目录的情况,我们必须递归的删除。于是,我们根据”分散难点”的思想,吧这个功能拆分为3个子方法:
(1)sftpGetFileList方法
这个方法是第一步,因为当你要递归从远程服务器指定目录删除目录时候,你必须首先要知道那个目录里面有那些文件,类似于使用FileZilla这种客户端工具时候,你可以去浏览目标机器上某目录下的所有文件。
我们在第139行定义了一个SFTPv3DirectoryEntry的List对象,然后在第141行用client.ls方法列出目标目录的所有的File,并且存入Vector中,然后从145-157航对其进行遍历,值得注意的是,因为这些操作仿造unix操作,就像我们用命令ls -l时候,它会吧当前目录"."和上层目录".."也计算在里面,所以我们必须将其排除,见第153行。
(2)sftpDeleteFolderRecursive方法
这个方法就是一个递归的方法,它用于递归的从远程服务器的目录删除目录。首先第183行,它调用(1)中的sftpGetFileList方法来获取了SFTPv3DirectoryEntry的List对象,然后在第187行开始遍历List对象,先在197-204行对于Entry是目录的情况进行了处理,它会递归的调用sftpDeleteFolderRecursive方法,然后在第204-211行则是对Entry是文件的情况进行了处理,直接调用已经提供的API,client.rm来移除这个文件。
(3)deleteFolderFromWebServer方法
这个方法是最终对外暴露的定义在接口中的方法,它在第15-39行对入参进行了检查,然后在第43-67行对于Connection对象的进行了非空检查,然后在第87行调用我们定义好的(2)中的sftpDeleteFolderResursive()方法来递归的删除远程服务器上指定目录下的某目录。
单元测试:
由于这个方法和deleteFileFromWebServer的行为极其相似,所以略去单元测试。