我正在用NetBeans構建一個GUI,並且GUI中的一個按鈕需要使用PowerShell腳本。我試圖獲取腳本的輸出並將其放入GUI中的JTextArea中。這是我到目前爲止。我做了一些調試,似乎掛在while循環中,但我爲什麼這樣做是困惑的。嘗試調用powershell腳本時Java程序掛起
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腳本,我試圖讓它使用它。
#Filename: hello1.ps1
Write-Host "Hello World!"
#End of Script
我做了一些研究,我發現,這是掛了其他人,但只是因爲他們忘了關閉進程的輸出流。
爲什麼要啓動命令處理器來啓動Powershell?此外,以非交互模式啓動Powershell可能更好(例如'powershell -NoLogo - 非交互式C:/ hello1.ps1') – ig0774
我同意@ig0774的兩點。在混合中添加cmd只是浪費時間和資源,而混濁水域並沒有提供任何好處。 Powershell.exe獨立。 – alroc
一旦我得到我的代碼工作,我會考慮這些建議。謝謝 – Franklin