我正在编写一个基本上通过java发送linux命令并打印回输出的程序。它工作正常,如果输出只有一行,但对于多行输出我无法弄清楚我做错了什么。例如,要检查我用的是“免费的”命令的内存使用情况,但它只返回线1和3。这里是我的代码:打印由BufferedReader返回的多行
if (clinetChoice.equals("3"))
{
String command = "free";
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println("You Chose Option Three");
String line;
while ((line = reader.readLine()) != null)
{
output += line;
System.out.println(line);
line = reader.readLine();
}
}
当我运行这个它只返回:
total used free share buffers cached
-/+ buffers/cache: 6546546 65464645
客户端代码:
while ((fromServer = input.readLine()) != null)
{
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye"))
break;
System.out.print("Enter your choice: ");
fromClient = stdIn.readLine().trim();
if(fromClient.equals("1"))
{
System.out.println("Client: " + fromClient);
output.println(fromClient);
}
if(fromClient.equals("2"))
{
System.out.println("Client: " + fromClient);
output.println(fromClient);
}
if(fromClient.equals("3"))
{
System.out.println("Client: " + fromClient);
output.println(fromClient);
}
if(fromClient.equals("4"))
{
System.out.println("Client: " + fromClient);
output.println(fromClient);
break;
}
}
这个答案是正确的,只是在'loop = reader.readLine();'在你的循环底部。 – lynks
这工作,谢谢。唯一的事情是它将同一行上的所有内容都返回。我添加了输出+ =行+“\ n”;但是一次只打印一行,而不是一次打印所有内容。 – Nick
@Nick:'readLine'消耗换行符,因此您需要将其添加回去。如果你想一次打印所有的输出,在你的循环中删除'println'并在循环之后执行'println(output)'。我将添加到这个答案 – pb2q