[자바] FTP 파일 전송

[자바] FTP 파일 전송

ftp를 사용하여

파일을 전송하는 경우 다음과 같이 한다.

1. ftp 선언 및 오픈

ftp = new FTPClient();

ftp.setControlEncoding("EUC-KR");

ftp.connect("아이피정보");

ftp.login("아이디", "비번");

2. 전송할 디렉토리를 생성한다

이떄 상위폴더가 존재하지 않는 경우 디렉토리는 생성되지 않는다

즉 전송할 서버에 "data" 라는 폴더가 존재하는 경우

"data/sub/cont" 라는 디렉토리를 생성할려고 하면 오류가 발생한다

data 는 존재하나 cont의 부모인 sub 가 존재하지 않아서다

글래서 디렉토리를 생성시는 다음과 같이 한다

boolean success = ftp.makeDirectory("저장할 폴더");

if (success) {

logger.info("[ FTP FILE make directory ] = Successfully created directory ");

} else {

logger.info("[ FTP FILE make directory ] = Failed to create directory. See server's reply.");

//--** 오류가 나는 경우 디렉트리 하나씩 생성

int dirStatus = 0;

String[] dir = strDivPath.split(separator);

String path = "";

for (String sdir : dir) {

if ("".equals(sdir)) {

continue;

}

path += separator + sdir;

dirStatus = ftp.cwd(path);

if(dirStatus == 550){ // 디렉토리 있는지 확인 없으면 생성

success = ftp.makeDirectory(path);

if (success) {

logger.info("[ FTP FILE sub make directory ] = Successfully created directory ==> " + path);

} else {

logger.info("[ FTP FILE sub make directory ] = Failed created directory ==> " + path);

}

}

}

}

3. 저장할 폴더로 디렉토리를 변경한다

ftp.changeWorkingDirectory("저장폴더"); // 디렉토리 변경

ftp.setFileType(FTP.BINARY_FILE_TYPE);

String tempFileName = new String(FileName.getBytes("euc-kr"),"iso_8859_1"); // 한글 깨짐 방지

4. 파일을 업로드한다

File uploadFile = new File("업로드할 파일 정보");

FileInputStream fis = null;

try

{

fis = new FileInputStream(uploadFile);

boolean isSuccess = ftp.storeFile(tempFileName, fis);

logger.info("[ FTP REPLY ] = " + ftp.getReplyString());

if (isSuccess){

logger.info("[ FTP RESULT ] = FTP Upload Success");

}

} catch (IOException ex){

logger.error(ex.getMessage());

} finally {

if (fis != null)

try{

fis.close();

} catch (IOException ex) {

}

}

ftp.logout();

} catch (SocketException e){

logger.error("FTP 전송중 오류가 발생했습니다 [SOCKET]==>" +e.getMessage());

} catch (IOException e){

logger.error("FTP 전송중 오류가 발생했습니다 [IO]==>" +e.getMessage());

} finally{

if (ftp != null && ftp.isConnected())

{

try

{

ftp.disconnect();

} catch (IOException e)

{

}

}

}

from http://iamfreenoble.tistory.com/8 by ccl(A) rewrite - 2021-11-11 15:28:11