使用 Java JSch 传输 SFTP 文件 [英] SFTP file transfer using Java JSch
本文介绍了使用 Java JSch 传输 SFTP 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码,它在远程服务器上检索文件内容并显示为输出.
Here is my code, which retrieves content of the file, on the remote server and display as output.
package sshexample;
import com.jcraft.jsch.*;
import java.io.*;
public class SSHexample
{
public static void main(String[] args)
{
String user = "user";
String password = "password";
String host = "192.168.100.103";
int port=22;
String remoteFile="sample.txt";
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
System.out.println("Creating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
System.out.println("SFTP Channel created.");
InputStream out= null;
out= sftpChannel.get(remoteFile);
BufferedReader br = new BufferedReader(new InputStreamReader(out));
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
br.close();
sftpChannel.disconnect();
session.disconnect();
}
catch(JSchException | SftpException | IOException e)
{
System.out.println(e);
}
}
}
现在如何实现这个将文件复制到本地主机的程序,以及如何将文件从本地主机复制到服务器.
Now how to implement this program that the file is copied in the localhost and how to copy a file from localhost to the server.
这里是如何处理任何格式文件的文件传输.
Here how to make work the transfer of files for any format of files.
推荐答案
使用 JSch 通过 SFTP 上传文件最简单的方法是:
The most trivial way to upload a file over SFTP with JSch is:
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");
同样下载:
sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");
<小时>
您可能需要处理UnknownHostKey
异常.em>
这篇关于使用 Java JSch 传输 SFTP 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文