您的位置:首页 > 其它

IO Foundation 12 - 下载远程文件到本地

2013-01-17 09:51 246 查看
需求:

在前面一篇文章中http://supercharles888.blog.51cto.com/609344/980336,我们已经介绍了如何创建一个到远程服务器的连接,那么这里我们就介绍如何通过这个连接来从远程服务器下载文件到本地。

实现:

源代码附上:

/**
* This method can do the Unix "scp" work ,it will copy the file from target
* server's root to local
*
* @param localPath
*            the path to local file system
* @param remotePath
*            the path which based on the htdocs of the web server directory
* @throws ParameterNullException ,ConfigureSystemException ,
DownloadFromWebServerException ,NetworkUnreachableException
*/
public void downloadFileFromWebServer(String remotePath, String localPath)
throws ParameterNullException, ConfigureSystemException,
DownloadFromWebServerException, NetworkUnreachableException {

// make sure whether the location to download is not null
if ((localPath == null) || (localPath.trim().equals(EMPTY_STRING))) {
logger.error(DOWNLOAD_FILE_PATH_TO_NULL);
throw new ParameterNullException(DOWNLOAD_FILE_PATH_TO_NULL);
}

// make sure whether the file that we need to download from is not null
if ((remotePath == null) || (remotePath.trim().equals(EMPTY_STRING))) {
logger.error(DOWNLOAD_FILE_PATH_FROM_NULL);
throw new ParameterNullException(DOWNLOAD_FILE_PATH_FROM_NULL);
}

// get the connection object
Connection conn = null;

try {
conn = getWebServerConnectionFactory().getServerMachineConnection();
// create a SCPClient based on the opened connection
SCPClient client = getSCPClient(conn) ;
// use the scp to copy the file(directory) from remote web server to
// local file system
client.get(webServerRoot + FORWARD_SLASH + remotePath, localPath);
} catch (NetworkUnreachableException ex) {
logger.error(FAILED_CONNECTION_TO_WS_SERVER + connFactory.getWebServerName());
throw new DownloadFromWebServerException(
FAILED_CONNECTION_TO_WS_SERVER + connFactory.getWebServerName(), ex);
}

catch (IOException ex) {
logger.error(SCP_IO_EXCEPTION);
throw new DownloadFromWebServerException(DOWNLOAD_FROM_WS_FAILED, ex);
}

finally {
if (conn != null) {
conn.close();
}
}

}

这个方法很简单,首先从17-25行还是对参数的非空检查,从第32行开始,我们先和以前一样获取ConnectionFactory,进而创建一个ethz.ssh2.Connection对象,然后我们第34行创建一个ScpClient对象,关键在于第35行,我们可以看到,它用了SCPClient的get方法来完成下载操作,它有2个参数,一个是远程目录,一个是本地目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  download IO 操作