1. Maven 依存関係を追加します
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.7.2</version>
</dependency>
1
2
3
4
5
2. Mainコード ブロック
パッケージ com.eurekaclient.utils;
com.jcraft.jsch.* をインポートします。
インポート lombok.extern.slf4j.Slf4j;
java.io.* をインポートします。
java.util.Propertiesをインポートします。
@Slf4j
パブリック クラス 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;
/**
* セッション
*/
プライベート静的セッション session = null;
/**
* 通道
*/
private static Channel チャネル = null;
/**
* FTP が接続されているかどうかを判断します
*
* @return
*/
public static boolean isOpen() { try { channelSftp = new ChannelSftp(); channelSftp.getServerVersion(); return true; } catch (Exception e) { log.error ("{}"、例: getMessage()); false を返します; }
}
/**
* ftp link
*/
public static void connectionFtp() { try { boolean open = isOpen(); if (!open) { // JSch オブジェクトを作成 JSch jsch = new JSch(); // ユーザー名、ホストアドレスを渡す、ポートはセッションオブジェクトを取得します session = 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)ファイル file = 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("ディレクトリの作成: {} ", mkdirs ); } // 書き込み可能 if (!files.canWrite()) { if (!files.setWritable(true)) { throw new FileNotFoundException(); }
文字
列ファイル名 = pathArry[pathArry.length - 1];
ファイル file = 新しいファイル (ローカルパス + ファイル名);
out = 新しい 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 voiddetach() { 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 ("そのようなファイルはありません".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 ファイルパス = 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 ( "ディレクトリの作成に失敗しました、{}"、e.getMessage()); } } } 3 番目に、クラスパッケージ com.eurekaclient.controller をテストします。
com.eurekaclient.utils.FtpUtils をインポートします。
インポート 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