怎么用java读取到另一台linux服务器的文件,给个例子
时间: 2024-03-05 14:54:30 浏览: 17
可以使用Java的SSH库来连接到Linux服务器,然后使用Java的IO库来读取文件内容。以下是一个简单的例子:
```java
import com.jcraft.jsch.*;
import java.io.*;
public class ReadLinuxFile {
public static void main(String[] args) {
String host = "your_linux_host";
String username = "your_username";
String password = "your_password";
String remoteFilePath = "/path/to/remote/file";
String localFilePath = "/path/to/local/file";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
InputStream inputStream = channelSftp.get(remoteFilePath);
OutputStream outputStream = new FileOutputStream(new File(localFilePath));
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
channelSftp.disconnect();
session.disconnect();
System.out.println("File downloaded successfully!");
} catch (JSchException | SftpException | IOException e) {
e.printStackTrace();
}
}
}
```
请注意,您需要将`your_linux_host`,`your_username`,`your_password`,`/path/to/remote/file`和`/path/to/local/file`替换为您自己的值。