maven 依赖:
<!-- https://mvnrepository.com/artifact/com.hierynomus/sshj -->
<dependency>
<groupId>com.hierynomus</groupId>
<artifactId>sshj</artifactId>
<version>0.34.0</version>
</dependency>
打开链接:
try (SSHClient sshClient = SSHClientUtil.getSSHClient("localhost", 22, "root", "123456");
SFTPClient sftpClient = sshClient.newSFTPClient()) {
} catch (IOException e) {
throw new RuntimeException(e);
}
执行 ls 命令输出路径:
for (RemoteResourceInfo remoteResourceInfo : sftpClient.ls("/data")) {
// System.out.println(remoteResourceInfo.getName());
System.out.println(remoteResourceInfo.getPath());
// System.out.println(remoteResourceInfo.getParent());
}
打开一个文本文件,并读取 128 字节的文件内容:
try (RemoteFile remoteFile = sftpClient.open("/data/temp/SFTP_TEST_FILE")) {
FileAttributes fileAttributes = remoteFile.fetchAttributes();
int maxPreviewSize = Math.toIntExact(128 > fileAttributes.getSize() ? fileAttributes.getSize() : 128);
byte[] fileBytes = new byte[maxPreviewSize];
remoteFile.read(0, fileBytes, 0, maxPreviewSize);
String fileContent = new String(fileBytes);
String[] fileLines = fileContent.split("\n");
// 最后一行可能为不完整数据,不取最后一行第内容
for (int i = 0; i < fileLines.length - 1; i++) {
System.out.println("文件第 " + i + "行:" + fileLines[i]);
}
// System.out.println("文件内容:" + fileContent);
System.out.println(fileAttributes.getSize());
System.out.println(remoteFile.getPath());
System.out.println(remoteFile.length());
}
打开一个文件并将文件输出到文件为流,合并两个文件流,然后保存到文件:
String fieldList = "name|password|age\n";
try (RemoteFile remoteFile = sftpClient.open("/data/temp/SFTP_TEST_FILE");
InputStream inputStream = remoteFile.new RemoteFileInputStream(0);
InputStream sequenceInputStream = new SequenceInputStream(new ByteArrayInputStream(fieldList.getBytes()), inputStream);
BufferedReader bfr = new BufferedReader(new InputStreamReader(sequenceInputStream));
OutputStream outputStream = new FileOutputStream("/data/temp/filemerge1.txt")) {
int tmp;
while ((tmp = sequenceInputStream.read()) != -1) {
outputStream.write(tmp);
}
// FileAttributes fileAttributes = remoteFile.fetchAttributes();
/*String line;
while ((line = bfr.readLine()) != null) {
System.out.println(line);
}*/
}
参考:
https://github.com/hierynomus/sshj
https://www.baeldung.com/java-file-sftp
https://stackoverflow.com/questions/35358762/list-all-files-in-remote-server-using-jsch