[英]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.