송민준의 개발노트

JAVA에서 SFTP 활용하기!! CSV 파일 적용(JSch 사용) 본문

JAVA

JAVA에서 SFTP 활용하기!! CSV 파일 적용(JSch 사용)

송민준 2020. 11. 8. 00:23

개발을 하다보면 파일질라나 putty 같은걸 사용하게 되는데...

프로그램에서 SFTP를 사용해서 개발해야 되는 경우가 있다!

 

우선 SFTP란 무엇인가??

FTP의 형태를 가지고 있지만 그 안에서는 SSH를 이용해 연결하는게 SFTP이다!

간단하게 FTP보다 보안이 강화된 전송 방식이다.

포트는 22( FTP의 경우 21)를 사용한다.

 

SFTP를 사용하기 위해 JSch라는 라이브러리를 다운 받았고 아래 링크에서 다운받으면 된다.

www.jcraft.com/jsch/

 

JSch - Java Secure Channel

JSch - Java Secure Channel JSch is a pure Java implementation of SSH2. JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is l

www.jcraft.com

 

해당 라이브러리를 다운받고 프로젝트에 넣어줬다면.... 아래와 같이 하면 된다.

 

★ 참고로 접속 정보를 2개를 해준 이유는 1개로 했을 경우 파일 옮기는게 잘 안된다.

Stackoverflow 형님들이 알려주신 정보로 요긴하게 써먹었다.

 

---- 클래스 내부 -------
private Session session = null; 
private Session toSession = null;
private Channel fromChannel = null; 
private Channel toChannel = null; 
private ChannelSftp fromChannelSftp = null;
private ChannelSftp toChannelSftp = null;

public void jschTest(파라미터 넣으셈)  throws Exception {
   // SFTP 서버 정보
   final String url = "111.111.111.111";
   final String user = "user";
   final String password = "password";
   final String path = "/folder1/folder2/";
   final String successPath = "/folder1/folder3/";

   JSch jsch = new JSch();
   try {
      // 세션 생성
      session = jsch.getSession(user, url);
      toSession = jsch.getSession(user, url);
      
      // 비밀번호 설정
      session.setPassword(password);
      toSession.setPassword(password);

      // 설정 정보
      Properties config = new Properties();

      // 호스트 정보 검사 안함
      config.put("StrictHostKeyChecking", "no");

      session.setConfig(config);
      toSession.setConfig(config);

      // 접속
      session.connect();
      toSession.connect();

      // sftp 채널접속
      fomChannel = session.openChannel("sftp");
      toChannel = toSession.openChannel("sftp");

      fromChannel.connect();
      toChannel.connect();

      fromChannelSftp = (ChannelSftp)fromChannel;
      toChannelSftp = (ChannelSftp)toChannel;
      
      // 파일경로 이동
      fromChannelSftp.cd(path);

      // 파일에 있는 모든 파일 불러옴
      Vector<ChannelSftp.LsEntry> fileList = fromChannelSftp.ls(path);
      
      // CSV 파일 불러옴
      for(int i = 0; i < fileList.size(); i++) {
         if(!fileList.get(i).getFilename().equals(".") && !fileList.get(i).getFilename().equals("..") && fileList.get(i).getFilename().endWith(".CSV")) {

            BufferedReader reader = new BufferedReader(new InputStreamReader(fromChannelSftp.get(fileList.get(i).getFileName())));
            String readStr == "";
            while((readStr = reader.readLine()) != null) {
               // CSV의 경우  ',' 로 구분해서 나옴
               String[] readArr = readStr.split(",");

               // 필요 로직 넣으셈
               
            }
         }
         // ----- 파일 이동하기 ------
         // 디렉토리 이동
         toChannelSftp.cd(successPath);
         // 파일 복사
         InputStream in = fromChannelSftp.get(fileList.get(i).getFilename());
         // 파일 붙여넣기
         toChannelSftp.put(in, fileList.get(i).getFilename());
         // 파일 삭제
         fromChannelSftp.rm(fileList.get(i).getFilename());
         reader.close();
      }
   }catch(Exception e) {
      throw e;
   } finally {
      // 자원 종료
      fromChannelSftp.quit();
      toChannelSftp.quit();
      session.disconnect();
      toSession.disconnect();
      fromChannel.disconnect();
      toChannel.disconnect();
   }

}
--------클래스 내부-----------------

'JAVA' 카테고리의 다른 글

제네릭이란...?  (0) 2021.01.17
기본자료형과 래퍼클래스 정리  (0) 2021.01.12
String 클래스 isEmpty 메소드  (2) 2020.04.16
JavaBean  (0) 2019.11.12
ASCII Table  (0) 2019.11.10