尝试调用Powershell脚本时Java程序挂起 [英] Java program hangs when trying to invoke powershell script

查看:90
本文介绍了尝试调用Powershell脚本时Java程序挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NetBeans构建GUI,并且GUI中的按钮之一需要使用powershell脚本.我正在尝试获取脚本的输出,并将其放入GUI中的JTextArea中.到目前为止,这就是我所拥有的.我做了一些调试,它似乎挂在while循环中,但是我对为什么这样做感到困惑.

I'm building a GUI with NetBeans, and one of the buttons in the GUI requires the use of a powershell script. I'm trying to get the script's output and put it into a JTextArea within the GUI. Here is what I have so far. I did a bit of debugging, and it seems to hang inside the while loop, but I'm confused as to why it's doing so.

private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    try {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec("cmd powershell C:/hello1.ps1");
        InputStream is = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader reader = new BufferedReader(isr);
        String line;
        while ((line = reader.readLine()) != null) {
            outputTextArea.setText(line);
        }
        reader.close();
        proc.getOutputStream().close();
    } catch (IOException ex) {
        Logger.getLogger(BatchFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

这是我要使其使用的简单Powershell脚本.

And here is a simple powershell script I'm trying to get it to work with.

#Filename: hello1.ps1
Write-Host "Hello World!"
#End of Script

我做了一些研究,发现它对其他人来说是挂的,但这仅仅是因为他们忘记了关闭流程输出流.

I did some researched, and I noticed that it was hanging for other people to, but only because they forgot to close the processes output stream.

推荐答案

我遇到了同样的问题.我将proc.getOutputStream().close()移到while循环之前,并且一切正常

I was having the same issue. I moved the proc.getOutputStream().close() before the while loop and everything worked

这篇关于尝试调用Powershell脚本时Java程序挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆