以下为SFTP的JAVA代码
java;gutter:true;
import com.jcraft.jsch.*;</p>
<p>import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;</p>
<p>public class SftpUtils {
private static ChannelSftp sftp = null;
private static Session session = null;
// 登录
public static void main(String [] ares){
try{
List str = readFile("test","127.0.0.1",22,"test","/data/postStore/data/1212121212.txt");
System.out.println(str.toString());
// putFile("postStoreFtp","127.0.0.1",22,"postStoreFtp","./data");
}catch (Exception e){</p>
<pre><code> }
}
public static ChannelSftp login(String userName,String host,int port,String password) throws JSchException {
JSch jSch = new JSch();
// 设置用户名和主机,端口号一般都是22
session = jSch.getSession(userName, host, port);
// 设置密码
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("connect success....");
return sftp;
}
// 退出登录
public static void logout() {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
}
public static List readFile(String userName, String host, int port, String password, String fPath){
BufferedReader reader = null;
List ls = new ArrayList<>();
// 登录sftp服务器
try {
ChannelSftp sftp = SftpUtils.login(userName,host,port,password);
// 构建文件输入流,读取文件内容取
reader = new BufferedReader(new InputStreamReader(sftp.get(fPath), StandardCharsets.UTF_8));
String str;
while((str = reader.readLine()) != null) {
ls.add(str);
}
reader.close();
//退出sftp
SftpUtils.logout();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return ls;
}
public static void putFile(String userName, String host, int port, String password, String fPath){
try {
ChannelSftp sftp = SftpUtils.login(userName,host,port,password);
sftp.cd(fPath);
File file = new File("E:\\1212121212.txt");
FileInputStream fileInputStream = new FileInputStream(file);
sftp.put(fileInputStream, file.getName());
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
//退出sftp
SftpUtils.logout();
}
</code></pre>
<p>}
Original: https://www.cnblogs.com/Dream-new/p/16435321.html
Author: Dream°
Title: Linux创建SFTP用户并使用jsch进行获取传输文件
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/523233/
转载文章受原作者版权保护。转载请注明原作者出处!