1

我正在编写一个基本上通过java发送linux命令然后打印输出的程序。如果输出只有一行,但对于多行输出,我无法弄清楚我做错了什么。例如,要检查内存使用情况,我使用“free”命令,但它只返回第 1 行和第 3 行。这是我的代码:

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;

        }


    }
4

3 回答 3

6

您正在调用readLine循环测试循环体。因此,对于循环的每次迭代,readLine都会调用两次,其中一个结果被丢弃:它没有被打印或添加到output. 这与您描述的结果相符。

这个循环应该足够了:

while ((line = reader.readLine()) != null)
{
    output += line + System.getProperty("line.separator");
    System.out.println(line);
}

如果您只是想打印一次整个输出,并且由于您在output变量中收集输出,您可以将println循环移出:

while ((line = reader.readLine()) != null)
{
    output += line + System.getProperty("line.separator");
}

System.out.println(output);
于 2012-09-10T17:30:48.197 回答
1

我应该指出,除了评论之外。使用readline()两次,您应该严格同时使用 stdout/stderr。否则你会冒着阻塞进程输出的风险,因为你没有使用它。有关更多信息,请参阅此 SO 答案

于 2012-09-10T18:34:19.813 回答
1

只需使用这个......你打电话readLine()两次......

while ((line = reader.readLine()) != null)
        {

            System.out.println(line);

        }

如果要将数据分配给输出变量..然后在 while 循环中执行此操作..

output = output + line;

于 2012-09-10T17:32:02.870 回答