我正在編寫一個基本上通過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