Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java program hangs when trying to invoke powershell script

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);
    }
}

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.

like image 800
Franklin Avatar asked Oct 18 '25 02:10

Franklin


1 Answers

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

like image 110
Tim Avatar answered Oct 20 '25 18:10

Tim