bufferedReader.readLine();总是返回null值

时间:2013-04-12 09:05:56

标签: java linux

我定义了一个函数来返回命令进程输出,在windows中工作正常,但在Linux中失败了。

Fro命令 ps -u root | grep java | awk'{print $ 1}'它始终返回 null

即使在执行此方法之前,我也尝试在命令提示符下执行命令,然后成功执行了

#ps -u root|grep java|awk '{print $1}'

385

2018

2048

4242

21290

25110

25589

26166

/**
 * This method will execute and returns the command output
 * @param commandToBeExecute
 * @return
 */
protected String getCMDOutput(final String commandToBeExecute)
{
    String cmdOutput = "";
    InputStream inputstream = null;
    InputStreamReader inputstreamreader = null;
    try 
    {
        final Process process = runTime.exec(commandToBeExecute);
        inputstream = process.getInputStream();
        inputstreamreader = new InputStreamReader(inputstream);
        bufferedReader = new BufferedReader(inputstreamreader);
        String currentLine;
        currentLine = bufferedReader.readLine();\\Always returning null for **ps -u root|grep java|awk '{print $1}'** command
        while(currentLine!=null)
        {
            cmdOutput += currentLine;
            currentLine = bufferedReader.readLine();
        }
    } 
    catch (IOException ioException) {
        logger.error(ioException.getMessage(), ioException);
    }
    finally
    {
        try
        {
            if(bufferedReader!=null)
            {
                bufferedReader.close();
            }
            if(inputstream!=null)
            {
                inputstream.close();
            }
            if(inputstreamreader!=null)
            {
                inputstreamreader.close();
            }           
        } 
        catch (IOException ioException) {
            logger.error(ioException.getMessage(), ioException);
        }
    }
    return cmdOutput;
}

当我尝试下面的代码时,它会给出错误

inputstream = process.getErrorStream();
        inputstreamreader = new InputStreamReader(inputstream);
        bufferedReader = new BufferedReader(inputstreamreader);
        currentLine = bufferedReader.readLine();

 (java.lang.String) ERROR: User name does not exist.

那么,这个错误的原因是什么,请指导解决以解决这个问题。

1 个答案:

答案 0 :(得分:0)

currentLine = bufferedReader.readLine();\\Always returning null for **ps -u root|grep java|awk '{print $1}'** command
        while(currentLine!=null)
        {
            cmdOutput += currentLine;
            currentLine = bufferedReader.readLine();
        }

将上述代码更改为:并尝试一次。

    while((currentLine = bufferedReader.readLine())!=null)
    {
        cmdOutput += currentLine;
        //currentLine = bufferedReader.readLine();
    }