需求:
在前面一篇文章中,我们已经介绍了如何创建一个到远程服务器的连接,那么这里我们就介绍如何通过这个连接来从远程服务器下载文件到本地。
实现:
源代码附上:
-
-
-
-
-
-
-
-
-
-
-
- public void downloadFileFromWebServer(String remotePath, String localPath)
- throws ParameterNullException, ConfigureSystemException,
- DownloadFromWebServerException, NetworkUnreachableException {
-
-
- if ((localPath == null) || (localPath.trim().equals(EMPTY_STRING))) {
- logger.error(DOWNLOAD_FILE_PATH_TO_NULL);
- throw new ParameterNullException(DOWNLOAD_FILE_PATH_TO_NULL);
- }
-
-
- if ((remotePath == null) || (remotePath.trim().equals(EMPTY_STRING))) {
- logger.error(DOWNLOAD_FILE_PATH_FROM_NULL);
- throw new ParameterNullException(DOWNLOAD_FILE_PATH_FROM_NULL);
- }
-
-
- Connection conn = null;
-
- try {
- conn = getWebServerConnectionFactory().getServerMachineConnection();
-
- SCPClient client = getSCPClient(conn) ;
-
-
- 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个参数,一个是远程目录,一个是本地目录
本文转自 charles_wang888 51CTO博客,原文链接:http://blog.51cto.com/supercharles888/1120358,如需转载请自行联系原作者