ファイルとフォルダーをアップロードするための sftp クライアントを実装する Java の関数コードの詳細な紹介
この記事では、ファイルやフォルダーをアップロードするための sftp クライアントを実装するための Java の関数コードを主に紹介します。興味のある方は学習してください。
1. 依存するjarファイルjsch-0.1.53.jar
2. ログイン方法にはパスワードログインとキーログインが含まれます
メイン関数:
import java.util.Properties; import com.cloudpower.util.Login; import com.util.LoadProperties; public class Ftp { public static void main(String[] args) { Properties properties = LoadProperties.getProperties(); Login.login(properties); } }
ログインページコード:
package com.cloudpower.util; import java.io.Console; import java.util.Properties; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class Login { public static void login(Properties properties) { String ip = properties.getProperty("ip"); String user = properties.getProperty("user"); String pwd = properties.getProperty("pwd"); String port = properties.getProperty("port"); String privateKeyPath = properties.getProperty("privateKeyPath"); String passphrase = properties.getProperty("passphrase"); String sourcePath = properties.getProperty("sourcePath"); String destinationPath = properties.getProperty("destinationPath"); if (ip != null && !ip.equals("") && user != null && !user.equals("") && port != null && !port.equals("") && sourcePath != null && !sourcePath.equals("") && destinationPath != null && !destinationPath.equals("")) { if (privateKeyPath != null && !privateKeyPath.equals("")) { sshSftp2(ip, user, Integer.parseInt(port), privateKeyPath, passphrase, sourcePath, destinationPath); } else if (pwd != null && !pwd.equals("")) { sshSftp(ip, user, pwd, Integer.parseInt(port), sourcePath, destinationPath); } else { Console console = System.console(); System.out.print("Enter password:"); char[] readPassword = console.readPassword(); sshSftp(ip, user, new String(readPassword), Integer.parseInt(port), sourcePath, destinationPath); } } else { System.out.println("请先设置配置文件"); } } /** * 密码方式登录 * * @param ip * @param user * @param psw * @param port * @param sPath * @param dPath */ public static void sshSftp(String ip, String user, String psw, int port, String sPath, String dPath) { System.out.println("password login"); Session session = null; JSch jsch = new JSch(); try { if (port <= 0) { // 连接服务器,采用默认端口 session = jsch.getSession(user, ip); } else { // 采用指定的端口连接服务器 session = jsch.getSession(user, ip, port); } // 如果服务器连接不上,则抛出异常 if (session == null) { throw new Exception("session is null"); } // 设置登陆主机的密码 session.setPassword(psw);// 设置密码 // 设置第一次登陆的时候提示,可选值:(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); // 设置登陆超时时间 session.connect(300000); UpLoadFile.upLoadFile(session, sPath, dPath); } catch (Exception e) { e.printStackTrace(); } System.out.println("success"); } /** * 密匙方式登录 * * @param ip * @param user * @param port * @param privateKey * @param passphrase * @param sPath * @param dPath */ public static void sshSftp2(String ip, String user, int port, String privateKey, String passphrase, String sPath, String dPath) { System.out.println("privateKey login"); Session session = null; JSch jsch = new JSch(); try { // 设置密钥和密码 // 支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了 if (privateKey != null && !"".equals(privateKey)) { if (passphrase != null && "".equals(passphrase)) { // 设置带口令的密钥 jsch.addIdentity(privateKey, passphrase); } else { // 设置不带口令的密钥 jsch.addIdentity(privateKey); } } if (port <= 0) { // 连接服务器,采用默认端口 session = jsch.getSession(user, ip); } else { // 采用指定的端口连接服务器 session = jsch.getSession(user, ip, port); } // 如果服务器连接不上,则抛出异常 if (session == null) { throw new Exception("session is null"); } // 设置第一次登陆的时候提示,可选值:(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); // 设置登陆超时时间 session.connect(300000); UpLoadFile.upLoadFile(session, sPath, dPath); System.out.println("success"); } catch (Exception e) { e.printStackTrace(); } } }
ファイルアップロードのコード:
package com.cloudpower.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Scanner; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class UpLoadFile { public static void upLoadFile(Session session, String sPath, String dPath) { Channel channel = null; try { channel = (Channel) session.openChannel("sftp"); channel.connect(10000000); ChannelSftp sftp = (ChannelSftp) channel; try { sftp.cd(dPath); Scanner scanner = new Scanner(System.in); System.out.println(dPath + ":此目录已存在,文件可能会被覆盖!是否继续y/n?"); String next = scanner.next(); if (!next.toLowerCase().equals("y")) { return; } } catch (SftpException e) { sftp.mkdir(dPath); sftp.cd(dPath); } File file = new File(sPath); copyFile(sftp, file, sftp.pwd()); } catch (Exception e) { e.printStackTrace(); } finally { session.disconnect(); channel.disconnect(); } } public static void copyFile(ChannelSftp sftp, File file, String pwd) { if (file.isDirectory()) { File[] list = file.listFiles(); try { try { String fileName = file.getName(); sftp.cd(pwd); System.out.println("正在创建目录:" + sftp.pwd() + "/" + fileName); sftp.mkdir(fileName); System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName); } catch (Exception e) { // TODO: handle exception } pwd = pwd + "/" + file.getName(); try { sftp.cd(file.getName()); } catch (SftpException e) { // TODO: handle exception e.printStackTrace(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < list.length; i++) { copyFile(sftp, list[i], pwd); } } else { try { sftp.cd(pwd); } catch (SftpException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("正在复制文件:" + file.getAbsolutePath()); InputStream instream = null; OutputStream outstream = null; try { outstream = sftp.put(file.getName()); instream = new FileInputStream(file); byte b[] = new byte[1024]; int n; try { while ((n = instream.read(b)) != -1) { outstream.write(b, 0, n); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { outstream.flush(); outstream.close(); instream.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } } } }
設定ファイルの読み取りコード:
package com.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class LoadProperties { public static Properties getProperties() { File file = new File(Class.class.getClass().getResource("/").getPath() + "properties.properties"); InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Properties properties = new Properties(); try { properties.load(inputStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return properties; } }
コードのディレクトリ構造:
テストの実行中に、設定ファイルをプロジェクトの bin ディレクトリに置きます (実行可能な jar ファイルにパッケージ化するときに削除します。パッケージ化が完了したら、設定ファイルと jar パッケージを同じディレクトリに置くだけです):
properties.properties
ip= user= pwd= port=22 privateKeyPath= passphrase= sourcePath= destinationPath=/home/dbbs/f
実行可能なjarファイルをパッケージ化します:
Export->java->Runnabe JAR file
完了後
コンソールでjava -jarを実行して名前をエクスポートしますjar パッケージの .jar を使用できます
上記は、ファイルとフォルダーをアップロードするための sftp クライアントを実装するための Java の関数コードの詳細な紹介です。関連コンテンツの詳細については、PHP 中国語 Web サイト (www.php) を参照してください。 .cn)!

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









Java の Weka へのガイド。ここでは、weka java の概要、使い方、プラットフォームの種類、利点について例を交えて説明します。

この記事では、Java Spring の面接で最もよく聞かれる質問とその詳細な回答をまとめました。面接を突破できるように。

Java 8は、Stream APIを導入し、データ収集を処理する強力で表現力のある方法を提供します。ただし、ストリームを使用する際の一般的な質問は次のとおりです。 従来のループにより、早期の中断やリターンが可能になりますが、StreamのForeachメソッドはこの方法を直接サポートしていません。この記事では、理由を説明し、ストリーム処理システムに早期終了を実装するための代替方法を調査します。 さらに読み取り:JavaストリームAPIの改善 ストリームを理解してください Foreachメソッドは、ストリーム内の各要素で1つの操作を実行する端末操作です。その設計意図はです

Java での日付までのタイムスタンプに関するガイド。ここでは、Java でタイムスタンプを日付に変換する方法とその概要について、例とともに説明します。

カプセルは3次元の幾何学的図形で、両端にシリンダーと半球で構成されています。カプセルの体積は、シリンダーの体積と両端に半球の体積を追加することで計算できます。このチュートリアルでは、さまざまな方法を使用して、Javaの特定のカプセルの体積を計算する方法について説明します。 カプセルボリュームフォーミュラ カプセルボリュームの式は次のとおりです。 カプセル体積=円筒形の体積2つの半球体積 で、 R:半球の半径。 H:シリンダーの高さ(半球を除く)。 例1 入力 RADIUS = 5ユニット 高さ= 10単位 出力 ボリューム= 1570.8立方ユニット 説明する 式を使用してボリュームを計算します。 ボリューム=π×R2×H(4

Spring Bootは、Java開発に革命をもたらす堅牢でスケーラブルな、生産対応のJavaアプリケーションの作成を簡素化します。 スプリングエコシステムに固有の「構成に関する慣習」アプローチは、手動のセットアップを最小化します。
