我遇到了一个我不知道会发生什么的问题。
我有一个类,它调用第二个类,通过ssh发送命令并返回结果。
结果是一个BufferedReader,然后在我的第一个类中处理这个结果。
头等舱:
.
.
.
String command = "ping " + ip + " -c 1";
BufferedReader result = instance.sendCommand(command);
// close only after all commands are sent
System.out.println("out of sshManager result : "+result);
System.out.println("out of sshManager line : "+result.readLine());
String line = null;
while ((line = result.readLine()) != null) {
System.out.println("out of sshManager line: "+line);
}二等舱:
public BufferedReader sendCommand(String command) throws JSchException, IOException {
//StringBuilder outputBuffer = new StringBuilder();
Channel channel = sesConnection.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.connect();
InputStream commandOutput = channel.getInputStream();
System.out.println("This is in sshmanager SSHManager: " + commandOutput);
result = new BufferedReader(new InputStreamReader(commandOutput));
String line = null;
System.out.println(" sshmanager result : " + result());
System.out.println(" sshmanager result line : " + result.readLine());
while ((line = result.readLine()) != null) {
System.out.println("in sshmanager: " + line);
}
System.out.println("in sshmanager result : " + result);
channel.disconnect();
return result;
}结果:
This is in sshmanager SSHManager: com.jcraft.jsch.Channel$MyPipedInputStream@40d5bd18
sshmanager result : java.io.BufferedReader@10a5ae6e
sshmanager result line : PING 192.168.11.11 (192.168.11.11) 56(84) bytes of data.
in sshmanager: From 192.168.11.77 icmp_seq=1 Destination Host Unreachable
in sshmanager:
in sshmanager: --- 192.168.11.11 ping statistics ---
in sshmanager: 1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 3006ms
in sshmanager:
in sshmanager result: java.io.BufferedReader@10a5ae6e
out of sshManager result: java.io.BufferedReader@10a5ae6e
out of sshManager line: null对象在我的第二个类中很好地创建,但是我不知道为什么,当我试图管理第一个类中的对象时,内容是空的。
你知道什么是问题吗?
发布于 2014-02-24 09:57:02
当文件返回到第一个方法时,BufferedReader已经读取了它。您可能希望返回一个包含文件内容的List<String>,而不是BufferedReader。
public List<String> sendCommand(String command) throws JSchException, IOException {
List<String> lines = new LinkedList<String>();
Channel channel = sesConnection.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.connect();
InputStream commandOutput = channel.getInputStream();
result = new BufferedReader(new InputStreamReader(commandOutput));
String line = null;
while ((line = result.readLine()) != null) {
lines.add(line);
}
channel.disconnect();
return lines;
}发布于 2014-02-24 09:57:25
这一切都来自于流媒体的概念。
一旦您在“第二类”中通过了流,您实际上就消耗了该流。所以,当你把它返回到“头等舱”的时候,流就完全消耗掉了。因此,您不能再流任何东西了。
请注意,即使将流包装到读取器中,读取操作(例如readLine)也被转发到流中。
发布于 2014-02-24 09:57:42
缓冲区读取器就像一串字节,您可以从(一次)读取这些字节。
您的基本问题是,在函数中,您已经从读取器中提取了文本,所以当您再次尝试时,只会得到null (因为读取器现在是,为空)。
https://stackoverflow.com/questions/21984154
复制相似问题