Java将文件上传到ftp服务器(ChannelSftp)

时间:2025-03-21 08:53:51
package com.eurekaclient.utils; import com.jcraft.jsch.*; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.util.Properties; @Slf4j public class FtpUtils { /** * ftp地址 */ private static final String ftpIp = "127.0.0.1"; /** * ftp端口 */ private static final String ftpPort = "22"; /** * ftp账户 */ private static final String ftpUserName = "admin"; /** * ftp密码 */ private static final String ftpPassWord = "admin"; /** * 超时时间 */ private static final String timeout = "6000"; /** * sftp对象 */ private static ChannelSftp channelSftp = null; /** * 会话 */ private static Session session = null; /** * 通道 */ private static Channel channel = 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链接 */ public static void connectionFtp() { try { boolean open = isOpen(); if (!open) { // 创建JSch对象 JSch jsch = new JSch(); // 通过 用户名,主机地址,端口 获取一个Session对象 session = jsch.getSession(ftpUserName, ftpIp, Integer.parseInt(ftpPort)); session.setPassword(ftpPassWord); // 为Session对象设置properties 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("上传图片starting"); connectionFtp(); if (null == channelSftp || channelSftp.isClosed()) { log.error("链接丢失"); } if (isExistDir(uploadPath)) { channelSftp.cd(uploadPath); } else { createDir(uploadPath, channelSftp); } File file = new File(localPath); io = new FileInputStream(file); channelSftp.put(io, file.getName()); log.info("上传图片ending"); } catch (Exception e) { log.error("{}", e.getMessage()); } finally { if (null != io) { try { io.close(); } catch (IOException e) { e.printStackTrace(); } } disconnect(); } } /** * @param downloadPath 下载文件地址 * @param localPath 本地文件地址 */ public static void downLoad(String downloadPath, String localPath) { FileOutputStream out = null; try { log.info("下载图片starting"); 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])) { continue; } 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("创建目录:{}", mkdirs); } // 可写 if (!files.canWrite()) { if (!files.setWritable(true)) { throw new FileNotFoundException(); } } String fileName = pathArry[pathArry.length - 1]; File file = new File(localPath + fileName); out = new FileOutputStream(file); channelSftp.get(downloadPath, out); } catch (Exception e) { log.error("{}", e.getMessage()); } finally { if (out != null) { try { out.close(); } catch (IOException e) { log.error("{}", e.getMessage()); } } disconnect(); } } /** * 关闭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 (Exception e) { if ("no such file".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 (String path : pathArry) { if ("".equals(path)) { continue; } filePath.append(path).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("创建目录失败,{}", e.getMessage()); } } }