[英]bufferedReader.readLine(); is always returning null value
我定义了一个函数来返回命令进程的输出,在Windows中它可以正常工作,但是在Linux中是失败的。
来回命令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.
那么,此错误的原因是什么,请指导解决以解决此问题。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.