需要導入jar:j2ssh-core-0.2.9.jar
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
public class GetMes {
public void getMessage(String path) {
String ip = "";
String catalogue = "";
String filename = "";
ip = path.substring(0, path.indexOf("#"));
catalogue = path.substring(path.indexOf("#") + 1, path.lastIndexOf("/") + 1);
filename = path.substring(path.lastIndexOf("/") + 1);
SshClient client = new SshClient();
try {
client.connect(ip, 22);
// 設置用戶名和密碼
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
pwd.setUsername("a");
pwd.setPassword("a");
int result = client.authenticate(pwd);
if (result == AuthenticationProtocolState.COMPLETE) {// 如果連接完成
OutputStream os = new FileOutputStream("d:/mail/" + filename);
client.openSftpClient().get(catalogue + filename, os);
File file = new File("d:/mail/" + filename);
if (!file.exists()) {
file.createNewFile();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 這裏的path是我自己約定的ip#catalogue的形式,
// 如果形式不同,方法體截取的方法只需做對應的修改即可。
String path = "10.100.133.11#/app/a.txt";
GetMes get = new GetMes();
get.getMessage(path);
}
}