상세 컨텐츠

본문 제목

java에서 sftp 연결하기

Java

by 탑~! 2014. 6. 10. 11:15

본문

ftp 연결하는 소스들은 많은데에 비해 sftp에 대한 소스들은 많이 부족한듯 싶다.

여기서 잠깐. sftp가 그럼 뭐냐?! 궁금한사람은 직접 정보의 바다에서 헤엄쳐보시길~!

일단. 이 포스트에서 사용한 코드를 사용하기 위해서는 특별한 jar 파일이 필요하다.

http://www.jcraft.com/jsch/ 이 곳에 들어가서 jsch-0.1.42.jar 를 받아두자.

그리고 이클립스에서 jar 파일을 가져와 셋팅~! 자...그럼 이제 준비가 끝났다.

아래에는 간단하게 sftp에 연결하고, 파일의 업로드, 다운로드를 하는 코드이다.

다른 블로그에 있는 소스를 참고해서 만드느라고 했는데 제대로 된 것인지 글쎄;;(실행은 잘 된다.)

이상한 점 첫 째는 public void disconnection() 의 메소드의 내용이 정확한 것인지 모르겠고

둘 째는 main 메소드를 실행하면 프로그램이 실행은 문제 없이 되지만 종료가 되지 않는 점이다.

(그런데 사이트에서 받은 예제 소스에서도 System.exit(0);을 사용하여 종료시킨다.)

왜그러지??ㅡㅅㅡ; 답을 아시는 분이 있음 나도좀 알려줘요~ㅋㄷ



package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.SftpException;

/**
 * 서버와 연결하여 파일을 업로드하고, 다운로드한다.
 *
 * @author haneulnoon
 * @since 2009-09-10
 *
 */
public class SFTPUtil{
    private Session session = null;

    private Channel channel = null;

    private ChannelSftp channelSftp = null;

    /**
     * 서버와 연결에 필요한 값들을 가져와 초기화 시킴
     *
     * @param host
     *            서버 주소
     * @param userName
     *            접속에 사용될 아이디
     * @param password
     *            비밀번호
     * @param port
     *            포트번호
     */
    public void init(String host, String userName, String password, int port) {
        JSch jsch = new JSch();
        try {
            session = jsch.getSession(userName, host, port);
            session.setPassword(password);

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }

        channelSftp = (ChannelSftp) channel;

    }

    /**
     * 하나의 파일을 업로드 한다.
     *
     * @param dir
     *            저장시킬 주소(서버)
     * @param file
     *            저장할 파일
     */
    public void upload(String dir, File file) {

        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            channelSftp.cd(dir);
            channelSftp.put(in, file.getName());
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 하나의 파일을 다운로드 한다.
     *
     * @param dir
     *            저장할 경로(서버)
     * @param downloadFileName
     *            다운로드할 파일
     * @param path
     *            저장될 공간
     */
    public void download(String dir, String downloadFileName, String path) {
        InputStream in = null;
        FileOutputStream out = null;
        try {
            channelSftp.cd(dir);
            in = channelSftp.get(downloadFileName);
        } catch (SftpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            out = new FileOutputStream(new File(path));
            int i;

            while ((i = in.read()) != -1) {
                out.write(i);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 서버와의 연결을 끊는다.
     */
    public void disconnection() {
        channelSftp.quit();

    }
}




[ 사용예]


public static void main(String args[]) {

        String host = "sftp주소";
        int port = 포트번호;
        String userName = "아이디";
        String password = "비밀번호";
        String dir = "/폴더명/"; //접근할 폴더가 위치할 경로
        String file = "f:\\test.txt(업로드시킬 파일)";

        UsingFTP util = new SFTPUtil();
        util.init(host, userName, password, port);
        util.upload(dir, new File(file));

String fileName="다운로드 받을 파일명"; //ex. "test.txt"
String saveDir="저장할 위치"//ex. "f:\\test3.txt"


        util.download(dir, fileName, saveDir);

        util.disconnection();
        System.exit(0);
    }




ex)
disconnection() 메서드에 session.disconnect(); 추가하시면 바로 종료하네요.


  1. fileName 이름을 전부 가지고 오는 메서드 1개 남기고 갑니다 추가해서 같이 사용하세요 파일을 여러개 다운받을때 필요합니다.
    public String[] getFileNames(String path,String regex) {
    // TODO Auto-generated method stub
    String [] getFile = null;
    Vector v = null;
    try{

    v = this.channelSftp.ls(path);
    Enumeration<Object> data = v.elements();
    int count = getDataCount(v, regex);
    int chk = 0;
    //System.out.println("count=" + count);

    getFile = new String[count];//배열초기화

    while(data.hasMoreElements() == true){//csv 파일만 이뤄진걸로 초기화 시켜야 한다.
    Object obj = data.nextElement();
    String csvData = obj.toString();
    //System.out.println("data=" + csvData);
    if(csvData.lastIndexOf(regex) > 0){
    //System.out.println("data=" + csvData.substring(csvData.indexOf("K"), csvData.lastIndexOf("v") + 1));
    getFile[chk] = csvData.substring(csvData.indexOf("K"), csvData.lastIndexOf("v") + 1);
    chk++;
    }
    }

    }catch(Exception e){
    System.err.println(e.getMessage());
    e.printStackTrace();
    }finally{

    }
    return getFile;
    }

    private int getDataCount(Vector v , String regex) {
    int count = 0;
    Enumeration<Object> data = v.elements();
    while(data.hasMoreElements() == true){//csv 파일만 이뤄진걸로 초기화 시켜야 한다.
    Object obj = data.nextElement();
    String csvData = obj.toString();
    if(csvData.lastIndexOf(regex) > 0){
    count++;//수를 증감시켜서 초기화 카운트를 얻어내야한다.
    }
    }
    return count;
    }

  2. out = new FileOutputStream(new File(path + downloadFileName));



출처 : http://haneulnoon.tistory.com/55


'Java' 카테고리의 다른 글

특정 url 소스 가져오기  (0) 2014.09.02
java document를 chm 파일로 다운로드  (0) 2014.06.10
MSSQL jdbc - sqljdbc.jar와 sqljdbc4.jar 차이  (0) 2013.03.19
자바소스 많은곳  (0) 2012.11.15
WebLogic 8.1 메뉴얼  (0) 2012.09.26

관련글 더보기