java从windows向linux传输文件
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
package com.ruoyi.xatool;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SFTPv3Client;
import ch.ethz.ssh2.Session;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class SSH2App {
private static final String host = "";
private static final String username = "";
private static final String password="";
private static final Connection conn = new Connection(host,2222);
//账密验证
private static boolean isAuthed(){
try {
return conn.authenticateWithPassword(username, password);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
//上传文件
public static void putFile(String localFile,String remoteTargetDirectory){
try {
conn.connect();
if(isAuthed()){
SCPClient scpClient = conn.createSCPClient();
scpClient.put(localFile, remoteTargetDirectory);
System.out.println("上传成功");
}else{
System.out.println("上传失败");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
conn.close();
}
}
//判断是否有该文件夹
public static boolean exec(String command,String url){
boolean flag =false;
try {
conn.connect();
if(isAuthed()){
SFTPv3Client sftpv3Client = new SFTPv3Client(conn);
Session session = conn.openSession();
session.execCommand(command);
InputStream input = session.getStdout();
byte[] data = new byte[1024];
int read = input.read(data);
//String result = new String(data,0,data.length);
if(read<1){
sftpv3Client.mkdir(url,0777);
System.out.println("创建文件夹:"+url);
}else{
flag = true;
}
}else{
System.out.println("authentication fail.");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
conn.close();
return flag;
}
}
//拼路径
public void isDir(String upUrl,String localUrl){
String[] split = upUrl.split("/");
String dirUrl ="/home/filebackup";
//判断是否有该村文件夹,split[split.length-2]==村名
String dir = "find "+dirUrl+" -name "+split[split.length-2]+" -type d";
boolean exec = exec(dir, upUrl);
if(!exec){
for (int i = 4; i < split.length; i++) {
dirUrl=dirUrl+"/"+split[i];
dir="find "+dirUrl+" -name "+split[i]+" -type d";
exec(dir,dirUrl);
}
}else{
//split[split.length-1]==村民姓名
dir = "find "+dirUrl+" -name "+split[split.length-1]+" -type d";
exec(dir,upUrl);
}
putFile(localUrl, upUrl);
}
public static void main(String[] args) throws UnsupportedEncodingException {
String dir = "";
String url="";
//isDir(url);
}
}
创建文件夹那里感觉还能优化,如果有大佬会的可以留言哦