기본 콘텐츠로 건너뛰기

Java SFTP 사용

1. jar(jsch-0.1.54.jar) 다운

http://www.jcraft.com/jsch/

2. 소스 예제

파일업로드 예시.
---------------------------------------------------------
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){
}

 /**
     * 하나의 파일을 다운로드 한다.
     *
     * @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();
            }

        }

    }

댓글

이 블로그의 인기 게시물

[Java] Http File Download 이어받기

Http 서버로부터 다운로드 받는 파일을 이어받기 위해서는 Http Header에 아래 두가지 정보를 추가해 주면 된다. URLConnection conn = url.openConnection(); conn.setRequestProperty("Accept-Ranges", "bytes"); conn.setRequestProperty("Range", "bytes=" + mOffset + "-"); 그러면 서버에서는 해당 Offset으로부터 File을 다운로드 시켜준다. 클라이언트가 요청헤더에 Range 필드를 포함 시켜서 보내면, 서버는 그 정보를 가지고 어디서 부터 파일을 보낼지 판단을 합니다. 하지만 클라이언트가(브라우저) Range 필드를 포함 시켜야 할지를 판단하는 기준은 최초 다운로드 요청시 서버의 응답헤더에 따라 다음 요청헤더에 Range 헤더를 생성할지 않할지 판단하게 됩니다. 그걸 당락짓는 응답 헤더 필드는 다음과 같습니다. Accept-Ranges , ETag, Last-Modified 반드시 위 필드를 응답 헤더에 같이 보내줘야 클라이언트는 다음 요청시 Range헤더를 포함시켜 보내게 됩니다. 참고로 말씀 드리면 위 필드를 포함 시켜서 보내더라도 value는 반드시 " " 로 묶어서 보내야 합니다. 안그러면 브라우저는 죽어도 Range 필드를 생성시키지 않습니다. HTTP 1.1 스펙은 따옴표를 강제적으로 해줘라 이런 내용 없습니다. 자바기준 40byte의 파일이라치면 클리이언트 요청을 두번으로 나누었다치면 이케 connection.setRequestProperty("Range", "bytes=0-20"); connection.setRequestProperty("Range", "bytes=20-40"); 단 co...

java 특정 디렉토리에 있는 파일 목록을 읽어내기, 정렬해서 가져오기

폴더 리스트 가져오기 String path="C:\"; File dirFile=new File(path); File []fileList=dirFile.listFiles(); for(File tempFile : fileList) {   if(tempFile.isFile()) {     String tempPath=tempFile.getParent();     String tempFileName=tempFile.getName();     System.out.println("Path="+tempPath);     System.out.println("FileName="+tempFileName);     /*** Do something withd tempPath and temp FileName ^^; ***/   } } 정렬해서 가져오기 import java.io.FileFilter; import java.io.IOException; import java.util.Arrays; import java.util.Date; import org.apache.commons.io.comparator.LastModifiedFileComparator; import org.apache.commons.io.filefilter.FileFileFilter; public class LastModifiedFileComparatorTest { public static void main(String[] args) throws IOException { File directory = new File("."); // get just files, not directories File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE); System.out.println("Defaul...