SFTPClient.java 6.14 KB
package com.sitech.util.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;

import org.apache.log4j.Logger;

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

/**
 * SFTP工具类
 *
 * @author   LINXC
 */
public class SFTPClient implements FTPIF{
	private Logger logger = Logger.getLogger(SFTPClient.class);

	private ChannelSftp sftp = null;
	private Session sshSession = null;
	
	public void login(String host, String username, String password)
			throws Exception {
		this.connect(host, 22, username, password);
	}

	public boolean store(String uploadFile, String toRfileName)
			throws Exception {
        String directory = "";
        if (toRfileName.lastIndexOf("/") != -1) {
            directory = toRfileName.substring(0, toRfileName.lastIndexOf("/"));
        }
		return upload(directory, uploadFile);
	}

	/***************************************************************************
	 * 连接SFTP服务器
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 * @throws Exception 
	 **************************************************************************/
	public boolean connect(String host, int port, String username,
			String password) throws Exception {
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			sshSession = jsch.getSession(username, host, port);
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no"); 
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			logger.info("Create sftp connection successful. ");
			return true;
		} catch (Exception e) {			
			throw e;
		}
	}

	/***************************************************************************
	 * 上传文件
	 * 
	 * @param directory
	 *            上传的目录
	 * @param uploadFile
	 *            要上传的文件
	 * @param sftp
	 **************************************************************************/
	public boolean upload(String directory, String uploadFile) {
		InputStream is = null;
		try {
            if (directory != "") {
                sftp.cd(directory);
            }
			File file = new File(uploadFile);
			is = new FileInputStream(file);
			sftp.put(is, file.getName());

			logger.info("Upload file[" + uploadFile + "] successful. ");
			return true;
		} catch (Exception e) {
			logger.error("Upload file[" + uploadFile + "] failed. ", e);
			return false;
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/***************************************************************************
	 * 下载文件
	 * 
	 * @param directory
	 *            下载目录
	 * @param downloadFile
	 *            下载的文件
	 * @param saveFile
	 *            存在本地的路径
	 * @param sftp
	 **************************************************************************/
	public void download(String directory, String downloadFile,
			String saveFile) {
		try {
			sftp.cd(directory);
			File file = new File(saveFile);
			sftp.get(downloadFile, new FileOutputStream(file));
			
			logger.info("Download file[" + downloadFile + "] successful. ");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("Download file[" + downloadFile + "] failed. ");
		}
	}

	/***************************************************************************
	 * 删除文件
	 * 
	 * @param directory
	 *            要删除文件所在目录
	 * @param deleteFile
	 *            要删除的文件
	 * @param sftp
	 **************************************************************************/
	public void delete(String directory, String deleteFile) {
		try {
			sftp.cd(directory);
			sftp.rm(deleteFile);
			logger.info("Delete file[" + deleteFile + "] successful. ");
		} catch (Exception e) {
			logger.info("Delete file[" + deleteFile + "] failed. ");
		}
	}

	/***************************************************************************
	 * 列出目录下的文件
	 * 
	 * @param directory
	 *            要列出的目录
	 * @param sftp
	 * @return
	 * @throws SftpException
	 **************************************************************************/
	@SuppressWarnings("unchecked")
	public Vector<LsEntry> listFiles(String directory)
			throws SftpException {
		return sftp.ls(directory);
	}

	public void logout() throws Exception {
		if(sftp != null){
			sftp.disconnect();
		}
		
		if(sshSession != null){
			sshSession.disconnect();
		}
		
	}


	public boolean chdir(String remoteDir) throws Exception {
		try{
			sftp.cd(remoteDir);
		}catch (Exception e) {
			throw e;
		}
		
		return true;
	}


	public RemoteFile[] listRemoteFile(String directory) throws Exception {
		Vector<LsEntry> temp = listFiles(directory);
		
		if (temp == null || temp.size() == 0) {
			return new RemoteFile[] {};
		}

		RemoteFile[] file = new RemoteFile[temp.size()];
		for (int i = 0; i < temp.size(); i++) {
			file[i] = new RemoteFile(temp.get(i));
		}
		
		return file;
	}
	
	public RemoteFile listRemoteFile(String directory, String fileName) throws Exception {
		Vector<LsEntry> temp = listFiles(directory);
		
		if (temp == null || temp.size() == 0) {
			return null;
		}
		
		for(LsEntry entry : temp){
			if(entry.getFilename().equals(fileName)){
				return new RemoteFile(entry);
			}
		}
		
		return null;
	}


	public boolean get(String fileName, String localFileName) throws Exception {
		File file = new File(localFileName);
		FileOutputStream fos = new FileOutputStream(file);
		sftp.get(fileName, fos);
		fos.close();
		return true;
	}


	public boolean rename(String fromName, String toName) throws Exception {
		try {
			sftp.rename(fromName, toName);
			return true;
		} catch (Exception e) {
			throw e;
		}
	}

}