使用jsch进行文件下载2---sftp客户端

8 篇文章 0 订阅
2 篇文章 0 订阅
public class SftpClient {
	private static Logger logger = LoggerFactory.getLogger(SftpClient.class);
	
	ChannelSftp sftp = null;
	Session sshSession = null;
	private String host= "";
	private int port = 0;
	private String userName = "";
	private String password = "";
	
	public SftpClient(String host,int port,String userName,String password) {
		this.host = host;
		this.userName = userName;
		this.port = port;
		this.password = password;
	}
	
   //建立连接
	public void connect() throws Exception {
		JSch jsch = new JSch();
		sshSession = jsch.getSession(this.userName,this.host,this.port);
		sshSession.setPassword(this.password);
		Properties sshConfig = new Properties();
		
		sshConfig.put("StrictHostKeyChecking", "no");
		sshSession.setConfig(sshConfig);
		sshSession.connect(20000);
		
		ChannelSftp channelSftp = (ChannelSftp)sshSession.openChannel("sftp");
        channelSftp.connect();
        this.sftp = channelSftp;	
		
		// 处理中文乱码
        Class cl = ChannelSftp.class;
        Field f1 =cl.getDeclaredField("server_version");
        f1.setAccessible(true);
        f1.set(sftp, 2);
        channelSftp.setFilenameEncoding("gbk");
	}
	
	public boolean isConnected() {
		if(null != sftp) {
			return sftp.isConnected();
		}
		return false;
	}
	
	public void disconnect() throws Exception {
		if(null != this.sftp) {
			if(this.sftp.isConnected()) {
				this.sftp.disconnect();
				sshSession.disconnect();
				logger.info(SftpClient.class+" DisConnected to "+this.host);
				return;
			} 
			
			if(this.sftp.isClosed()) {
				logger.info(SftpClient.class + "sftp is closed already");
			}
		}
	}
	
	public void upload(String directory,String uploadFile) throws Exception {
		if( (null != directory) && (!directory.trim().equals(""))) {
			this.sftp.cd(directory);
		}
			File file = new File(uploadFile);
			FileInputStream in = FileUtils.openInputStream(file);
			this.sftp.put(in,file.getName());
			
			IOUtils.closeQuietly(in);
		
	}
	
	public void uploadByDirectory(String directory) throws Exception {
		String uploadFile = "";
		List<String> uploadFileList = listFiles(directory);
		Iterator<String> it = uploadFileList.iterator();
		
		while(it.hasNext()) {
			uploadFile = it.next().toString();
			upload(directory,uploadFile);
		}
	}
	
	public void download(String directory, String downloadFile,
			String saveDirectory) throws Exception {
		String saveFile = saveDirectory + File.separator + downloadFile;
 
		this.sftp.cd(directory);
		File file = new File(saveFile);
		this.sftp.get(downloadFile, new FileOutputStream(file));
	}

	public boolean downloadAndRename(String directory, String downloadFile,
			String saveDirectory, String rename) {
		String saveFile = saveDirectory + File.separator + rename;
		OutputStream fos = null;
		try {
			fos = new FileOutputStream(saveFile);
			this.sftp.cd(directory);
			this.sftp.get(downloadFile, fos);
		} catch(Exception e){
			logger.error("下载sftp图片异常:"+downloadFile,e);
			return false;
		}finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					logger.error("关闭sftp异常", e);
				}
			}
		}
		
		return  true;
	}

	public void downloadByDirectory(String directory, String saveDirectory)
			throws Exception {
		String downloadFile = "";
		List<String> downloadFileList = listFiles(directory);
		Iterator<String> it = downloadFileList.iterator();

		while (it.hasNext()) {
			downloadFile = it.next().toString();
			if (downloadFile.toString().indexOf(".") >= 0) {
				download(directory, downloadFile, saveDirectory);
			}
		}
	}

	public void delete(String directory, String deleteFile) throws Exception {
		this.sftp.cd(directory);
		this.sftp.rm(deleteFile);
	}

	public List<String> listFiles(String directory) throws Exception {
		List<String> fileNameList = new ArrayList();

		Vector fileList = this.sftp.ls(directory);
		Iterator it = fileList.iterator();

		while (it.hasNext()) {
			String fileName = ((ChannelSftp.LsEntry) it.next()).getFilename();
			if ((!".".equals(fileName)) && (!"..".equals(fileName))) {

				fileNameList.add(fileName);
			}
		}

		return fileNameList;
	}

	public void rename(String directory, String oldFileNm, String newFileNm)
			throws Exception {
		this.sftp.cd(directory);
		this.sftp.rename(oldFileNm, newFileNm);
	}

	public void cd(String directory) throws Exception {
		try {
			this.sftp.cd(directory);
		} catch (SftpException exception) {
			if (ChannelSftp.SSH_FX_NO_SUCH_FILE == exception.id) {
				this.sftp.mkdir(directory);
				this.sftp.cd(directory);
			} else {
				throw exception;
			}
		}
	}

	/**
	 * 校验文件是否存在
	 * @param directory
	 * @return
	 */
	public boolean get(String directory)  {
		try {
			 this.sftp.get(directory);
			return true;
		} catch (SftpException e) {
			return false;
		}
	}

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值