Java - JSch를 사용하여 SFTP 파일 업로드 하기

* JSch 라이브러리를 사용하여 SFTP 접속 및 파일 업로드
  (http://www.jcraft.com/jsch/)


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


JSch jsch = new JSch();
Session session = null;
ChannelSftp channelSftp = null;
   
/**
 * SFTP 접속
 * @param ip 아이피
 * @param port 포트
 * @param id 로그인아이디
 * @param pw 로그인비밀번호
 */
public void connect(String ip, int port, String id, String pw)
{
    // 연결 시도
    session = jsch.getSession(id, ip, port);
    session.setPassword(pw);
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect(); 
   
    // 방식 설정
    Channel channel = session.openChannel("sftp");
    channel.connect();
    channelSftp = (ChannelSftp)channel;
}

/**
 * SFTP 접속 종료
 */
public void disconnect()
{
    if (channelSftp != null)
        channelSftp.disconnect();

    if (session != null)
        session.disconnect();
}
   
/**
 * 폴더 확인 및 생성
 * @param dir 폴더명(경로포함)
 */
public void checkDir(String dir)
{
    SftpATTRS attrs = null;

    // 폴더 체크
    try
    {
        attrs = channelSftp.stat(dir);
    }
    catch(Exception e)
    {
        attrs = null;
    }
   
    // attrs가 널이면 폴더 존재 X
    if (attrs == null)
    {
        channelSftp.mkdir(dir); // 폴더 생성
    }
}
   
   
/**
 * 폴더 이동
 * @param dir 폴더명(경로포함)
 */
public void moveDir(String dir)
{
    // 폴더 이동..
    channelSftp.cd(dir);
}   
   
/**
 * 파일 업로드.
 * @param fileName 파일명(경로포함)
 * @param fileData 파일내용
 * @return
 */
public boolean fileUpload(String fileName, byte[] fileData)
{
    OutputStream os = channelSftp.put(fileName);
    os.write(fileData);
    os.flush();
    os.close();
}