1. maven 종속성 추가
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.7.2</version>
</dependency>
1
2
3
4
5
2. 메인 코드 블록
패키지 com.eurekaclient.utils;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.Properties;
@Slf4j
공개 클래스 FtpUtils {
/**
* ftp address
*/
private static final String ftpIp = "127.0.0.1";
/**
* ftp port
*/
private static final String ftpPort = "22";
/**
* ftp account
*/
private static final String ftpUserName = "admin";
/**
* ftp 비밀번호
*/
private static final String ftpPassWord = "admin";
/**
* timeout time
*/
private static final String timeout = "6000";
/**
* sftp object
*/
개인 정적 ChannelSftp channelSftp = null;
/**
* 세션
*/
개인 정적 세션 세션 = null;
/**
* 通道
*/
비공개 정적 채널 채널 = null;
/**
* ftp가 연결되었는지 확인
*
* @return
*/
public static boolean isOpen() { try { channelSftp = new ChannelSftp(); channelSftp.getServerVersion(); return true; } catch (Exception e) { log.error ("{}", e.getMessage()); return false; }
}
/**
* ftp link
*/
public static void connectionFtp() { try { boolean open = isOpen(); if (!open) { // JSch 객체 생성 JSch jsch = new JSch(); // 사용자 이름, 호스트 주소 전달 , 포트는 세션 개체 세션 가져오기 = jsch.getSession(ftpUserName, ftpIp, Integer.parseInt(ftpPort)); session.setPassword(ftpPassWord);
// Session 객체의 속성 설정
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// 시간 제한 설정
session.setTimeout(Integer.parseInt(timeout) ) );
// 연결 설정
session.connect();
// SFTP 채널 열기
channel = session.openChannel("sftp");
// SFTP 채널 연결 설정
channel.connect();
channelSftp = (ChannelSftp) channel ;
}
} catch (Exception e) { log.error("{}", e.getMessage());
}
}
/**
* @param uploadPath 업로드 파일 주소
* @param localPath 로컬 파일 주소
*/
public static void uploadImage(String uploadPath, String localPath) { FileInputStream io = null; try { log.info("업로드 이미지 시작"); connectionFtp (); if (null == channelSftp || channelSftp.isClosed()) { log.error("링크 손실"); } if (isExistDir(uploadPath)) { channelSftp.cd(uploadPath); } else { createDir(uploadPath , channelSftp); } 파일 파일 = new File(localPath);
io = 새로운 FileInputStream(파일);
channelSftp.put(io, file.getName());
log.info("최종종료");
} catch(예외 e) { log.error("{}", e.getMessage()); } 마지막으로 { if (null != io) { try { io.close(); } catch (IOException e) { e.printStackTrace(); } } 연결 해제(); }
}
/**
* @param downloadPath 다운로드 파일 주소
* @param localPath 로컬 파일 주소
*/
public static void downLoad(String downloadPath, String localPath) { FileOutputStream out = null; try { log.info("다운로드 이미지 시작"); connectionFtp (); if (null == channelSftp || channelSftp.isClosed()) { log.error("링크 손실"); } String[] pathArry = downloadPath.split("/"); StringBuffer filePath = new StringBuffer(" /"); for (int i = 0; i < pathArry.length - 1; i++) { if ("".equals(pathArry[i])) {
계속;
}
filePath.append(pathArry[i]).append("/");
}
channelSftp.cd(filePath.toString());
log.info("현재 디렉토리: {}", channelSftp.pwd( ) );
//로컬 디렉토리가 있는지 판단
File files = new File(localPath);
if (!files.exists()) { boolean mkdirs = files.mkdirs(); log.info("Create directory: {} ", mkdirs ); } // 쓰기 가능 if (!files.canWrite()) { if (!files.setWritable(true)) { throw new FileNotFoundException(); }
}
String fileName = pathArry[pathArry.length - 1];
파일 파일 = 새 파일(localPath + 파일 이름);
out = new FileOutputStream(파일);
channelSftp.get(downloadPath, out);
} catch(예외 e) { log.error("{}", e.getMessage()); } 마지막으로 { if (out != null) { try { out.close(); } catch (IOException e) { log.error("{}", e.getMessage()); } } 연결 해제(); } }
/**
* ftp 연결
*/
public static void disconnect() { if (channelSftp.isConnected()) { session.disconnect(); channelSftp.disconnect(); } }
/**
* 디렉토리 존재 여부 확인 및 생성
*/
public static boolean isExistDir(String directory) { boolean isDirExistFlag = false; try { SftpATTRS sftpAttrS = channelSftp.lstat(directory); isDirExistFlag = true; return sftpAttrS.isDir( } catch (예외 e) { if ("해당 파일 없음".equals(e.getMessage().toLowerCase())) { isDirExistFlag = false; } } return isDirExistFlag; }
/**
* @param createpath 文件目录地址
*/
public static void createDir(String createpath, ChannelSftp sftp) throws Exception { try { String[] pathArry = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (문자열 경로: pathArry) { if ("".equals(path)) { 계속; } filePath.append(경로).append("/"); if (isExistDir(filePath.toString())) { sftp.cd(filePath.toString()); } else { // 建立目录
sftp.mkdir(filePath.toString());
// 현재 디렉토리로 입력 및 설정
sftp.cd(filePath.toString());
}
}
channelSftp.cd(createpath);
} catch (SftpException e) { log.error ( "Failed to create directory, {}", e.getMessage()); } } } 셋째, 테스트 클래스 패키지 com.eurekaclient.controller;
import com.eurekaclient.utils.FtpUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
공개 클래스 FtpController {
public static void main(String[] args) { try { FtpUtils.uploadImage("/vsftp/data/test/", "D:\\images\\063c6aa05dfa49acb705f928f5e5f3a8.jpg"); FtpUtils.downLoad("/vsftp/data/test/063c6aa05dfa49acb705f928f5e5f3a8.jpg", "D:\\images\\"); } catch(예외 e) { log.info("{}", e.getMessage()); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
—————————————————
저작권: 이 기사는 CSDN 블로거 "Weiwei~"의 원본 기사이며 CC 4.0 BY-SA 저작권 계약을 따릅니다. 원본 소스 링크와 이 기사의 진술.
원본 링크: https://blog.csdn.net/weixin_42906244/article/details/126406329