[java] sftp 연결해서 파일 업로드.

|

http://www.jcraft.com/jsch/ 이 곳에 들어가서 jsch-0.1.42.jar 를 받아 jar 파일을 추가해준다.


파일업로드 예시.

---------------------------------------------------------

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;


//    private 로 선언해줌.

private Session session = null;

private Channel channel = null;

private ChannelSftp channelSftp = null;


//    sftp 연결.

 /**
     * 서버와 연결에 필요한 값들을 가져와 초기화 시킴
     * @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;

    }


//    파일 업로드.

    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();

            }

        }

    }


//    연결끊기.

    public void disconnection() {

        channelSftp.quit();

    }



//    호출.

try{

                String host = "***.***.***.***;

                String userName = "test";

                String password = "1234567890";

                int port = ***;

                String sftpdir = ""; //접근할 폴더가 위치할 경로

               

                init(host, userName, password, port);

                upload(sftpdir, new File()); 

                disconnection();

}

catch (Exception e){

}

'저장용 > java' 카테고리의 다른 글

keystore 비밀번호 변경하기.  (0) 2016.05.24
[java] 형변환 str to int , int to str  (0) 2015.08.11
[java] sftp 파일삭제.  (0) 2015.07.01
[java] split 사용시 참고.  (0) 2015.03.22
And