从Java调用Powershell会执行infinate

时间:2014-09-18 10:04:12

标签: java eclipse powershell command

我试图从java程序调用powershell命令,我可以用下面的代码实现它。但问题是执行powershell命令后代码不会停止。

此代码打印powershell命令输出。但是它正在执行infinate [打印输出后执行没有停止]。

有谁知道这里的错误是什么?

Java代码:

public class PowerShellHelper 
{
public ProcessBuilder processbuilder = null; 
public Process process = null;

public PowerShellHelper() 
{

}

String execPowerShell()
{   
    String command = "Get-WmiObject Win32_Process -filter ProcessId=5988";
    String[] cmds = {"powershell.exe",command};
    String result= null;
    try
    {
        processbuilder = new ProcessBuilder(cmds);
        processbuilder.redirectErrorStream(true);           
        process = processbuilder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null ;
        while (true)
        {                        
            line = r.readLine();
            if(line == null) {break;}
            System.out.println(line);
        }
        process.getOutputStream().close();

    }
    catch(Exception e)
    {
        System.out.println("Exception "+e);
    }
    return result;
}

public static void main(String[] args) 
{
    PowerShellHelper psh  = new PowerShellHelper();
    psh.execPowerShell();   
}

}

1 个答案:

答案 0 :(得分:0)

只需添加:

process.getOutputStream().close();
打开BufferedReader后

。 这应该可以解决问题。