java读取服务器上文件,java 读取linux服务器上文件
时间: 2023-07-18 19:24:01 浏览: 44
可以使用Java中的SSH库(如Jsch)来连接到Linux服务器,并使用Java中的标准输入/输出流来读取文件。
以下是一个简单的示例代码:
```java
import com.jcraft.jsch.*;
import java.io.*;
public class ReadFileFromServer {
public static void main(String[] args) {
String user = "username"; // 服务器用户名
String host = "hostname"; // 服务器地址
int port = 22; // SSH端口号
String password = "password"; // 服务器密码
String remoteFile = "/path/to/remote/file"; // 远程文件路径
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("cat " + remoteFile);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
channel.disconnect();
session.disconnect();
} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们使用Jsch库连接到服务器,并使用SSH通道执行命令“cat”来读取远程文件的内容。然后,我们使用标准输入流读取通道的输出,并将其打印到控制台上。