JAVA SSH 连接服务器 去指定目录 检查文件 并读取json文件内容
要使用Java SSH连接服务器并检查文件,可以使用JSch库。以下是一个示例代码:
import com.jcraft.jsch.*; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class SSHExample { public static void main(String[] args) { String host = "your_host"; int port = 22; String username = "your_username"; String password = "your_password"; String remoteDirectory = "/path/to/remote_directory"; String fileName = "your_file.json"; try { JSch jsch = new JSch(); Session session = jsch.getSession(username, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; sftpChannel.cd(remoteDirectory); InputStream inputStream = sftpChannel.get(fileName); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder jsonContent = new StringBuilder(); while ((line = reader.readLine()) != null) { jsonContent.append(line); } System.out.println("JSON content: " + jsonContent.toString()); reader.close(); sftpChannel.disconnect(); session.disconnect(); } catch (JSchException | SftpException | Exception e) { e.printStackTrace(); } } }
请注意替换your_host
,your_username
,your_password
,/path/to/remote_directory
和your_file.json
为实际的服务器和文件信息。
以上代码将连接到远程服务器,将工作目录更改为指定的目录,然后从服务器上获取指定的JSON文件并读取其内容。
pom导入
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>