java服务器间文件传输,java实现在多服务器之间的文件传输(Jsch)
java實現在多服務器之間的文件傳輸(Jsch)
JSch 是SSH2的一個純Java實現。它允許你連接到一個sshd 服務器,使用端口轉發,X11轉發,文件傳輸等等。
我主要是今天完成個分布式架構下獲取其他服務器文件流的功能,順便記一下。這個還是很簡單的。
我用的是1.54版本,就這個版本用的人最多。這是地址: https://mvnrepository.com/artifact/com.jcraft/jsch/0.1.54
關于咋用,看下面代碼,必要的注釋都寫了。其實也就是指定好地址、端口號、賬戶密碼,連上然后就可以操作了。
package com.skypyb.util;
import com.jcraft.jsch.*;
import java.io.File;
import java.io.InputStream;
import java.util.Properties;
public class JschFTPFile {
private static Channel channel = null;
public static String getPath(String filesPath,String fileName) {
String separator = File.separator;//系統的分割符
String fileName = new StringBuffer(filesPath)
.append(separator)
.append(fileName).toString();
return fileName;
}
public static InputStream getTaskFile(String path) {
InputStream download = null;
try {
Channel channel = getChannel();
download = download(path, (ChannelSftp) channel);
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
return download;
}
private static Channel getChannel() throws JSchException {
if (channel != null) return channel;
//聲明JSCH對象
JSch jSch = new JSch();
//獲取一個Linux會話
Session session = jSch.getSession("root", "127.0.0.1", 22);
//設置登錄密碼
session.setPassword("614");
//關閉key的檢驗
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
//連接Linux
session.connect();
//通過sftp的方式連接
ChannelSftp ch = (ChannelSftp) session.openChannel("sftp");
ch.connect();
channel = ch;
return channel;
}
public static InputStream download(String downloadFile, ChannelSftp sftp) throws SftpException {
InputStream inputStream = sftp.get(downloadFile);
return inputStream;
}
}
總結
以上是生活随笔為你收集整理的java服务器间文件传输,java实现在多服务器之间的文件传输(Jsch)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017阿里校招内推面试回忆
- 下一篇: python展开_python实现傅里叶