JAVA 는 jcraft 를 사용 하여 SFTP 도구 류 를 조작 합 니 다.

16898 단어 JAVA
jcraft 패키지 다운로드:https://download.csdn.net/download/ruixue0117/10922182
도구 류 용 도 는 Linux 에 파일 서버 를 구축 하고 업로드 와 다운로드 모두 파일 흐름 방식 (Resquest 와 Response 사용) 을 사용 합 니 다.
기능 은 업로드 다운로드, 대량 업로드 다운로드, 파일 스 트림 업로드 (Request), 다운로드 기록 파일 스 트림 (Response), 파일 내용 직접 읽 기, 파일 직접 쓰기, 디 렉 터 리 작업, 파일 삭제 등 을 포함한다.
SFtpUtils.java
package hh.com.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Vector;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

import hh.com.exception.CustomException;

/**
 * SFTP   
 * 
 * @author xxx
 * @date 2019-1-17
 * @version 1.0
 */
public class SFtpUtils {

	private static Log logger = LogFactory.getLog(SFtpUtils.class);

	// FTP  
	private String ftpName;
	// FTP      
	private String username;
	// FTP     
	private String password;
	// FTP      IP  
	private String host;
	// FTP   
	private int port;
	//    
	private ResourceBundle property = null;
	//         
	private String configFile = "ftpconfig";
	//     
	private String encoding = "utf-8";
	//    
	private String homeDir = "/ftp/fs01/";
	
	private ChannelSftp sftp = null;
	private Session sshSession = null;
	
	public SFtpUtils(String ftpName) {
		this.ftpName = ftpName;
		setArg(configFile);
	}

	public static void main(String[] args) {
		SFtpUtils sftp = null;
		//       
		String localPath = "E:\\logs\\";
		// Sftp    
		String sftpPath = "/SFTP_FILES/TEST/";
		try {
			sftp = new SFtpUtils("ATTACHMENT_");
			sftp.uploadFile(new FileInputStream(new File(localPath + "logs.txt")), "logs.txt", sftpPath);
			sftp.downFile("/SFTP_FILES/TEST/", "logs.txt", "E:\\logs\\", "logs2.txt");
			sftp.writeToFtp("/SFTP_FILES/TEST/logs1.txt", "          。");
			StringBuffer sb = sftp.readFile("/SFTP_FILES/TEST/logs1.txt");
			System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *     
	 * @param configFile        
	 */
	private void setArg(String configFile) {
		try {
			property = ResourceBundle.getBundle(configFile);
			username = property.getString(ftpName+"username");
			password = property.getString(ftpName+"password");
			host = property.getString(ftpName+"host");
			port = Integer.parseInt(property.getString(ftpName+"port"));
		} catch (Exception e) {
			System.out.println("     " + configFile + "     !");
		}
	}

	/**
	 *   SFTP     
	 */
	private void connect() {
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			sshSession = jsch.getSession(username, host, port);
			if (logger.isInfoEnabled()) {
				logger.info("Session created.");
			}
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			if (logger.isInfoEnabled()) {
				logger.info("Session connected.");
			}
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			if (logger.isInfoEnabled()) {
				logger.info("Opening Channel.");
			}
			sftp = (ChannelSftp) channel;
			if (logger.isInfoEnabled()) {
				logger.info("Connected to " + host + ".");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *     
	 */
	private void disconnect() {
		if (this.sftp != null) {
			if (this.sftp.isConnected()) {
				this.sftp.disconnect();
				if (logger.isInfoEnabled()) {
					logger.info("sftp is closed already");
				}
			}
		}
		if (this.sshSession != null) {
			if (this.sshSession.isConnected()) {
				this.sshSession.disconnect();
				if (logger.isInfoEnabled()) {
					logger.info("sshSession is closed already");
				}
			}
		}
	}

	/**
	 *       
	 * 
	 * @param remotPath:      (       ,       eg:/assess/sftp/jiesuan_2/2014/)
	 * @param localPath:      (       ,D:\Duansha\sftp\)
	 * @param fileFormat:      (       ,      )
	 * @param fileEndFormat:      (    )
	 * @param del:       sftp  
	 * @return
	 */
	public List batchDownFile(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del) {
		List filenames = new ArrayList();
		boolean _flag = false;
		try {
			if (!isConnect()){
				connect();
				_flag = true;
			}
			Vector v = listFiles(remotePath);
			if (v.size() > 0) {
				Iterator it = v.iterator();
				while (it.hasNext()) {
					LsEntry entry = (LsEntry) it.next();
					String filename = entry.getFilename();
					SftpATTRS attrs = entry.getAttrs();
					if (!attrs.isDir()) {
						boolean flag = false;
						String localFileName = localPath + filename;
						fileFormat = fileFormat == null ? "" : fileFormat.trim();
						fileEndFormat = fileEndFormat == null ? "" : fileEndFormat.trim();
						//     
						if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
							if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
								flag = downFile(remotePath, filename, localPath, filename);
								if (flag) {
									filenames.add(localFileName);
									if (flag && del) {
										deleteSFTP(remotePath, filename);
									}
								}
							}
						} else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
							if (filename.startsWith(fileFormat)) {
								flag = downFile(remotePath, filename, localPath, filename);
								if (flag) {
									filenames.add(localFileName);
									if (flag && del) {
										deleteSFTP(remotePath, filename);
									}
								}
							}
						} else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
							if (filename.endsWith(fileEndFormat)) {
								flag = downFile(remotePath, filename, localPath, filename);
								if (flag) {
									filenames.add(localFileName);
									if (flag && del) {
										deleteSFTP(remotePath, filename);
									}
								}
							}
						} else {
							flag = downFile(remotePath, filename, localPath, filename);
							if (flag) {
								filenames.add(localFileName);
								if (flag && del) {
									deleteSFTP(remotePath, filename);
								}
							}
						}
					}
				}
			}
			if (logger.isInfoEnabled()) {
				logger.info("download file is success:remotePath=" + remotePath + "and localPath=" + localPath + ",file size is" + v.size());
			}
		} catch (SftpException e) {
			e.printStackTrace();
		} finally {
			if (_flag)
				disconnect();
		}
		return filenames;
	}

	/**
	 *       
	 * 
	 * @param remotPath:      (       )
	 * @param remoteFileName:     
	 * @param localPath:      (       )
	 * @param localFileName:     
	 * @return
	 */
	public boolean downFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
		FileOutputStream fieloutput = null;
		boolean _flag = false;
		try {
			if (!isConnect()){
				connect();
				_flag = true;
			}
			File file = new File(localPath + localFileName);
			fieloutput = new FileOutputStream(file);
			sftp.get(homeDir + remotePath + remoteFileName, fieloutput);
			if (logger.isInfoEnabled()) {
				logger.info("DownloadFile:" + remoteFileName + " success from sftp.");
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != fieloutput) {
				try {
					fieloutput.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (_flag)
				disconnect();
		}
		return false;
	}
	
	/**
	 *       
	 * 
	 * @param remotePath:      
	 * @param remoteFileName:     
	 * @param response
	 * @return
	 */
	public boolean downFile(String remotePath, String newFileName, HttpServletResponse response) {
		OutputStream outputStream = null;
		boolean _flag = false;
		try {
			if (!isConnect()){
				connect();
				_flag = true;
			}
			//      
			response.reset(); //     
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment; filename=" + new String(newFileName.getBytes("GBK"), "ISO-8859-1"));
			
			outputStream = response.getOutputStream();
			sftp.get(homeDir + remotePath, outputStream);
			outputStream.flush();
			outputStream.close();
			if (logger.isInfoEnabled()) {
				logger.info("DownloadFile:" + newFileName + " success from sftp.");
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != outputStream) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (_flag)
				disconnect();
		}
		return false;
	}
	
	/**
	 *     
	 * @param remoteFileName
	 * @return
	 */
	public StringBuffer readFile(String remoteFileName) {
		StringBuffer resultBuffer = new StringBuffer();
		InputStream in = null;
		boolean _flag = false;
		try {
			if (!isConnect()) {
				connect();
				_flag = true;
			}
			
			in = sftp.get(homeDir + remoteFileName);
			if(in == null) return resultBuffer;
			
			BufferedReader br = new BufferedReader(new InputStreamReader(in, encoding));
			String data = null;
			try {
				while ((data = br.readLine()) != null) {
					resultBuffer.append(data + "
"); } } catch (IOException e) { logger.error(" 。"); e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); logger.debug(" !", e); } finally { try { if (in != null) in.close(); } catch (Exception e) { // e.printStackTrace(); } if (_flag) disconnect(); } return resultBuffer; } /** * FTP * @param path * @param content */ public void writeToFtp(String path, String content) throws CustomException,Exception{ boolean _flag = false; try { if (!isConnect()) { connect(); _flag = true; } String remoteFileName = path.substring(path.lastIndexOf("/") + 1); String remotePath = path.substring(0, path.lastIndexOf("/") + 1); InputStream in = new ByteArrayInputStream(content.getBytes(encoding)); uploadFile(in, remoteFileName, remotePath); } catch (Exception e) { e.printStackTrace(); logger.debug(" !", e); throw new CustomException(path + " !"); } finally { if (_flag) disconnect(); } } /** * * * @param remotePath: * @param remoteFileName: * @param localPath: ( ) * @param localFileName: * @return */ public boolean uploadFile(InputStream in, String remoteFileName, String remotePath) { boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } createDir(remotePath); sftp.put(in, remoteFileName); return true; } catch (SftpException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (_flag) disconnect(); } return false; } /** * * * @param remotePath: * @param localPath: ( ) * @param del: * @return */ public boolean bacthUploadFile(String remotePath, String localPath, boolean del) { boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } File file = new File(localPath); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile() && files[i].getName().indexOf("bak") == -1) { if (this.uploadFile(new FileInputStream(files[i]), files[i].getName(), remotePath) && del) { deleteFile(localPath + files[i].getName()); } } } if (logger.isInfoEnabled()) { logger.info("upload file is success:remotePath=" + remotePath + "and localPath=" + localPath + ",file size is " + files.length); } return true; } catch (Exception e) { e.printStackTrace(); } finally { if (_flag) this.disconnect(); } return false; } /** * * * @param filePath * @return */ public boolean deleteFile(String filePath) { File file = new File(filePath); if (!file.exists()) { return false; } if (!file.isFile()) { return false; } boolean rs = file.delete(); if (rs && logger.isInfoEnabled()) { logger.info("delete file success from local."); } return rs; } /** * * * @param createpath * @return */ public boolean createDir(String createpath) { boolean _flag = false; createpath = homeDir + createpath; try { if (!isConnect()){ connect(); _flag = true; } if (isDirExist(createpath)) { this.sftp.cd(createpath); return true; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if (isDirExist(filePath.toString())) { sftp.cd(filePath.toString()); } else { // sftp.mkdir(filePath.toString()); // sftp.cd(filePath.toString()); } } this.sftp.cd(createpath); return true; } catch (SftpException e) { e.printStackTrace(); } finally { if (_flag) disconnect(); } return false; } /** * * * @param directory * @return */ public boolean isDirExist(String directory) { boolean isDirExistFlag = false; boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } SftpATTRS sftpATTRS = sftp.lstat(directory); isDirExistFlag = true; return sftpATTRS.isDir(); } catch (Exception e) { if (e.getMessage().toLowerCase().equals("no such file")) { isDirExistFlag = false; } } finally { if (_flag) disconnect(); } return isDirExistFlag; } /** * stfp * * @param directory: * @param deleteFile: * @param sftp */ public void deleteSFTP(String directory, String deleteFile) { boolean _flag = false; try { if (!isConnect()){ connect(); _flag = true; } sftp.rm(homeDir + directory + deleteFile); if (logger.isInfoEnabled()) { logger.info("delete file success from sftp."); } } catch (Exception e) { e.printStackTrace(); } finally { if (_flag) disconnect(); } } /** * * * @param path */ public void mkdirs(String path) { File f = new File(path); String fs = f.getParent(); f = new File(fs); if (!f.exists()) { f.mkdirs(); } } /** * * * @param directory: * @param sftp * @return * @throws SftpException */ public Vector listFiles(String directory) throws SftpException { boolean _flag = false; if (!isConnect()){ connect(); _flag = true; } Vector ls = sftp.ls(homeDir + directory); if (_flag) disconnect(); return ls; } public boolean isConnect() { return (this.sftp != null && this.sftp.isConnected() && this.sshSession != null && this.sshSession.isConnected()); } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public ChannelSftp getSftp() { return sftp; } public void setSftp(ChannelSftp sftp) { this.sftp = sftp; } }

ftpconfig.properties
#FTP    
#============Attachment============#
ATTACHMENT_username=sftp_hrdms
ATTACHMENT_password=sftp_hrdms2019
ATTACHMENT_host=192.168.1.203
ATTACHMENT_port=22

ATTATEST_username=root
ATTATEST_password=123123123
ATTATEST_host=120.79.79.189
ATTATEST_port=22

좋은 웹페이지 즐겨찾기