详解sftp实现对远程服务器的文件操作

该所有操作依赖的jsch的jar包     jsch-0.1.50.jar

 以下为本人整理的相关SFTP对服务器文件的相关操作,具体的操作方方法依赖于ChannelSftp对象,刻字机单独进行封装,本处就不贴出完整的工具类了


1:获得 ChannelSftp对象


public class SftpUtil {
	private static final Logger LOG = LogManager.getLogger(SftpUtil.class);
	private static SftpUtil sftpUtil;
	private static ChannelSftp sftp;
	private String host;
	private int port;
	private String userName;
	private String password;

	private SftpUtil(String host, int port, String userName, String password) {
		this.host = host;
		this.port = port;
		this.userName = userName;
		this.password = password;
	}

	/**
	 * 获得Smb连接对象
	 * 
	 * @Title: getInstance
	 * @param url
	 * @return SmbUtil
	 * @author wangqinghua
	 * @date 2015-9-22 下午7:39:41
	 */
	public static synchronized SftpUtil getInstance(String host, int port,
			String userName, String password) {
		if (sftpUtil == null) {
			sftpUtil = new SftpUtil(host, port, userName, password);
		}
		return sftpUtil;
	}

	/**
	 * 连接初始化
	 * 
	 * @Title: init void
	 * @author wangqinghua
	 * @date 2015-9-22 下午7:40:50
	 */
	public ChannelSftp getSftp() {
		JSch jsch = new JSch();
		Channel channel = null;
		try {
			Session sshSession = jsch.getSession(this.userName, this.host, this.port);
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect(20000);
			channel = sshSession.openChannel("sftp");
			channel.connect();
		} catch (JSchException e) {
			LOG.info("getSftp exception:", e);
		}
		return (ChannelSftp) channel;
	}
        public void disconnect() throws Exception {
            if (sftp != null) {
               if (sftp.isConnected()) {
                    sftp.disconnect();
               } else if (sftp.isClosed()) {
                    System.out.println("Session close...........");
               }
            }
        }
}

 2:SFTP上传单个文件

/**
	 * SFTP上传单个文件
	 * 
	 * @Title: upload
	 * @param directory
	 * @param uploadFile
	 * @throws Exception
	 *             void
	 * @author wangqinghua
	 * @date 2015-9-24 下午1:49:55
	 */
	public void upload(String directory, String uploadFile) throws Exception {
		sftp.cd(directory);
		File file = new File(uploadFile);
		sftp.put(new FileInputStream(file), file.getName());
	}


3.上传目录下的所有文件(批量上传)

/**
	 * 上传目录下的所有文件(批量上传)
	 * 
	 * @Title: uploadByDirectory
	 * @param directory
	 * @throws Exception
	 *             void
	 * @author wangqinghua
	 * @date 2015-9-24 下午1:50:53
	 */
	public void uploadByDirectory(String directory) throws Exception {
		String uploadFile = "";
		List uploadFileList = this.listFiles(directory);
		Iterator it = uploadFileList.iterator();
		while (it.hasNext()) {
			uploadFile = it.next().toString();
			this.upload(directory, uploadFile);
		}
	}

4:通过SFTP下载文件

/**
	 * 通过SFTP下载文件
	 * 
	 * @Title: download
	 * @param directory
	 * @param downloadFile
	 * @param saveDirectory
	 * @throws Exception
	 *             void
	 * @author wangqinghua
	 * @date 2015-9-24 下午1:56:22
	 */
	public void download(String directory, String downloadFile,
			String saveDirectory) throws Exception {
		String saveFile = saveDirectory + "//" + downloadFile;
		sftp.cd(directory);
		File file = new File(saveFile);
		sftp.get(downloadFile, new FileOutputStream(file));
	}

5:批量下载目录下的文件


/**
	 * 批量下载目录下的文件
	 * 
	 * @Title: downloadByDirectory
	 * @param directory
	 * @param saveDirectory
	 * @throws Exception
	 *             void
	 * @author wangqinghua
	 * @date 2015-9-24 下午1:58:17
	 */
	public void downloadByDirectory(String directory, String saveDirectory)
			throws Exception {
		String downloadFile = "";
		List downloadFileList = this.listFiles(directory);
		Iterator it = downloadFileList.iterator();
		while (it.hasNext()) {
			downloadFile = it.next().toString();
			if (downloadFile.toString().indexOf(".") < 0) {
				continue;
			}
			this.download(directory, downloadFile, saveDirectory);
		}
	}

6:删除文件

/**
	 * 删除文件
	 * 
	 * @Title: delete
	 * @param directory
	 * @param deleteFile
	 * @throws Exception
	 *             void
	 * @author wangqinghua
	 * @date 2015-9-24 下午1:58:57
	 */
	public void delete(String directory, String deleteFile) throws Exception {
		sftp.cd(directory);
		sftp.rm(deleteFile);
	}

7:文件重命名

/**
	 * 文件重命名
	 * 
	 * @Title: rename
	 * @param directory
	 * @param oldFileNm
	 * @param newFileNm
	 * @throws Exception
	 *             void
	 * @author wangqinghua
	 * @date 2015-9-24 下午2:02:22
	 */
	public void rename(String directory, String oldFileNm, String newFileNm)
			throws Exception {
		sftp.cd(directory);
		sftp.rename(oldFileNm, newFileNm);
	}

8:获得文件流

/**
	 * 获得文件流
	 * 
	 * @Title: get
	 * @param directory
	 * @return
	 * @throws Exception
	 *             InputStream
	 * @author wangqinghua
	 * @date 2015-9-24 下午2:03:41
	 */
	public InputStream getInputStream(String directory) throws Exception {
		InputStream streatm = sftp.get(directory);
		return streatm;
	}

9:Servlet结合SFTP实现简单的文件下载


/**
	 * Servlet结合SFTP实现简单的文件下载
	 * @Title: doPost
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 * void
	 * @author wangqinghua 
	 * @date 2015-9-24 下午2:15:40
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		LOG.info("进入下载文件开始..........");
		String host = "";// 主机地址
		String port = "";// 主机端口
		String username = "";// 服务器用户名
		String password = "";// 服务器密码
		String planPath = "";// 文件所在服务器路径
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		OutputStream fos = null;

		String fileName = "demo";
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		String currentDate = formatter.format(new Date());
		// demo20150924.txt
		String downloadFile = fileName + currentDate + ".zip";

		PrintWriter out = null;
		SftpUtil sftpUtil = new SftpUtil(host, Integer.parseInt(port),
				username, password);
		try {
			ChannelSftp sftp=sftpUtil.getSftp();
			String filename = "";
			// String[] strs=planUrl.split("/");
			String filePath = planPath;
			// 列出目录下的文件
			List listFiles = listFiles(filePath);
			boolean isExists = listFiles.contains(downloadFile);
			if (isExists) {
				sftp.cd(filePath);
				if (sftp.get(downloadFile) != null) {
					bis = new BufferedInputStream(sftp.get(downloadFile));
				}
				filename = downloadFile;
				fos = response.getOutputStream();
				bos = new BufferedOutputStream(fos);
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/x-msdownload;charset=utf-8");
				final String agent = request.getHeader("User-Agent");
				String attachment = "attachment;fileName=";
				String outputFilename = null;

				if (agent.indexOf("Firefox") > 0) {
					attachment = "attachment;fileName*=";
					outputFilename = "=?UTF-8?B?"
							+ (new String(Base64.encodeBase64(filename
									.getBytes("UTF-8")))) + "?=";
					;
				} else {
					if (agent.indexOf("MSIE") != -1) {
						outputFilename = new String(filename.getBytes("gbk"),"iso8859-1");
					} else {
						outputFilename = new String(filename.getBytes("UTF-8"), "iso8859-1");
					}
				}
				response.setHeader("Content-Disposition", attachment + outputFilename);
				int bytesRead = 0;
				// 输入流进行先读,然后用输出流去写,下面用的是缓冲输入输出流
				byte[] buffer = new byte[8192];
				while ((bytesRead = bis.read(buffer)) != -1) {
					bos.write(buffer, 0, bytesRead);
				}
				bos.flush();
				LOG.info("文件下载成功");
			} else {
				response.setCharacterEncoding("utf-8");
				response.setContentType("text/html; charset=UTF-8");
				out = response.getWriter();
				out.println("" + "" + "没有找到你要下载的文件" + ""
						+ "");
			}
		} catch (Exception e) {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html; charset=UTF-8");
			out = response.getWriter();
			out.println("" + "" + "没有找到你要下载的文件" + ""
					+ "");
		} finally {
			try {
				sftp.disconnect();
				LOG.info("SFTP连接已断开");
			} catch (Exception e) {
				e.printStackTrace();
			}

			if (out != null) {
				out.close();
			}
			LOG.info("out已关闭");
			if (bis != null) {
				bis.close();
			}
			LOG.info("bis已关闭");
			if (bos != null) {
				bos.close();
			}
			LOG.info("bos已关闭");
		}
	}

10:获得目录下的所有文件名

/**
	 * 获得目录下的所有文件名
	 * 
	 * @Title: listFiles
	 * @param directory
	 * @return
	 * @throws Exception
	 *             List
	 * @author wangqinghua
	 * @date 2015-9-24 下午1:53:40
	 */
	@SuppressWarnings("rawtypes")
	public List listFiles(String directory) throws Exception {
		Vector fileList;
		List fileNameList = new ArrayList();
		fileList = sftp.ls(directory);
		Iterator it = fileList.iterator();
		while (it.hasNext()) {
			String fileName = ((LsEntry) it.next()).getFilename();
			if (".".equals(fileName) || "..".equals(fileName)) {
				continue;
			}
			fileNameList.add(fileName);
		}
		return fileNameList;
	}

关于sftp内部方法详情 :http://blog.csdn.net/jr_soft/article/details/18704857


你可能感兴趣的:(JAVA)