1. 程式人生 > >詳解sftp實現對遠端伺服器的檔案操作

詳解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<String> uploadFileList = this.listFiles(directory);
		Iterator<String> 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<String> downloadFileList = this.listFiles(directory);
		Iterator<String> 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<String> 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("<html >" + "<body>" + "沒有找到你要下載的檔案" + "</body>"
						+ "</html>");
			}
		} catch (Exception e) {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html; charset=UTF-8");
			out = response.getWriter();
			out.println("<html >" + "<body>" + "沒有找到你要下載的檔案" + "</body>"
					+ "</html>");
		} 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<String>
	 * @author wangqinghua
	 * @date 2015-9-24 下午1:53:40
	 */
	@SuppressWarnings("rawtypes")
	public List<String> listFiles(String directory) throws Exception {
		Vector fileList;
		List<String> fileNameList = new ArrayList<String>();
		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