728x90
자바 jcraft 라이브러리를 사용하여 SFTP 서버 통신 및 파일 다운로드 예제입니다.
서버의 IP와 아이디, 비밀번호 포트 번호까지 정확하게 입력하셔야 하고,
경로 부분 직접 작성해주셔야 합니다.
또한 Main이 없기때문에 해당 클래스 호출하는 Main 메소드 따로 작성해주셔야 하니 참고 부탁드립니다.
package noah;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
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;
import com.jcraft.jsch.ChannelSftp.LsEntry;
public class SftpClient {
/// Fields
private Session session = null;
private Channel channel = null;
private ChannelSftp channelSftp = null;
private static final String host = "IP";
private static final String userName = "ID";
private static final String password = "PW";
private static final int port = port;
/// Constructor
public SftpClient(){
// SFTP 연결
connect();
// SFTP 파일 다운로드
fileDownload();
// 연결 끊기
disconnection();
}
/// Method
public void connect(){
JSch jsch = new JSch();
try{
// Jsch 세션 생성
session = jsch.getSession(userName, host, port);
session.setPassword(password);
// 세션과 관련된 정보 설정
Properties config = new Properties();
// 호스트정보 검사 하지 않음.
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
} catch(JSchException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
channelSftp = (ChannelSftp) channel;
}
public void fileDownload(){
InputStream is = null;
FileOutputStream out = null;
String date = "210322";
String path = "경로";
try {
// 경로 이동
channelSftp.cd(path);
// 해당 경로 파일 리스트 받아오기
Vector<ChannelSftp.LsEntry> fileList = channelSftp.ls(path);
// LsEntry 건수 만큼 처리
for(LsEntry entry : fileList){
// 경로에서 받은 파일명 변수 처리
String fileName = entry.getFilename();
// [. , ..] 경로 파일명이 아니면서, 파일 명에 -가 포함되어있고 요청하는 date로 끝나는 파일명 있는가?
if(!fileName.equals(".") && !fileName.equals("..") && fileName.contains("-") && fileName.endsWith(date)){
// 파일 GET
is = channelSftp.get(fileName);
// 원하는 경로에 파일 생성
File localFile = new File("./log/"+fileName);
out = new FileOutputStream(localFile);
int readCount = 0;
while( (readCount = is.read()) > 0 ){
out.write(readCount);
}
is.close();
out.close();
}
}
} catch (SftpException se) {
se.printStackTrace();
} catch ( Exception e){
e.printStackTrace();
}
}
public void disconnection() {
channelSftp.quit();
channel.disconnect();
session.disconnect();
}
}
728x90
'BACK-END > JAVA' 카테고리의 다른 글
[Java] 로그 생성 파일 경로 추출 (0) | 2021.04.19 |
---|---|
[Java] 알고리즘 문자열 2진 검색(Binary Search) 예제 (0) | 2021.04.16 |
자바 제어자 (Modifier) (0) | 2019.03.19 |
자바 접근제어자(Access Modifier) (0) | 2019.03.18 |
OOP(Object Oriented Programming) (0) | 2019.03.16 |