Java 实现 SFTP 上传文件

直接上代码:

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

/**
 * SFTP,连接,文件上传
 * @author lc
 * @web www.liuchang.org
 * 2015-10-29
 */
public class SFTPUtil {
	public static String SUCCESS = "S";
	public static String ERROR = "E";
	
	private ChannelSftp sftp = null;
	Session sshSession = null;
	
	public ChannelSftp connect(String host, int port, String username, 
			String password){
		
		JSch jsch = null;
		try {
			jsch = new JSch();
			jsch.getSession(username, host, port);
			sshSession = jsch.getSession(username, host, port);
			System.out.println("Session created.");
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			System.out.println("Session connected.");
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			System.out.println("Connected to " + host + ".");
		} catch (RuntimeException e) {
			disconnect();
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
		catch (Exception e) {
			disconnect();
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
		
		return sftp;
	}
	
	public String uploadFile(String directory, String uploadFile, String saveFileName){
		if(sftp == null){
			return ERROR;
		}
		
		try {
			sftp.cd(directory);
			File file=new File(uploadFile);
			sftp.put(new FileInputStream(file), saveFileName);
		} catch (Exception e) {
			disconnect();
			e.printStackTrace();
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	public void disconnect(){
		if(sshSession != null){
			sshSession.disconnect();
		}
		if(sftp != null){
			sftp.disconnect();	
		}
	}
}

 

发表评论