我的 Java 程序正在 Windows 机器上运行。从这台 Windows 机器上,我需要从 Linux 服务器读取一个文件。 我已经编写了这段代码来对 Linux 服务器进行身份验证,并且它工作正常
session = jsch.getSession("root", "ServerIP", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("Passwrod");
session.connect();
System.out.println("Server is connect");
我可以看到“Server is connect”正在我的机器上打印,这意味着身份验证已通过服务器完成。 现在需要从这个服务器读取文件,我已经写了这段代码
try
{
File file = new File("/var/log//callrec/core1.log");
LineNumberReader sc = new LineNumberReader(new FileReader(file));
}
catch(Exception e)
{
e.printStackTrace();
}
但是它抛出文件未找到异常。 任何人都可以指导我如何解决这个问题。
最佳答案
根据 http://www.jcraft.com/jsch/examples/ScpFrom.java.html ,你需要通过你的session
对象在远程端执行命令,然后获取输入和输出流与远程命令通信,并通过这些 channel 读取文件元数据和内容:
...
String command = "scp -f /var/log/callrec/core1.log";
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
// Now use in and out to read the file,
// see http://www.jcraft.com/jsch/examples/ScpFrom.java.html for a complete example
...
关于java - 通过java程序从Linux服务器读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21132861/