3

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

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

我做了一些研究,我注意到它正在等待其他人,但这只是因为他们忘记关闭进程输出流。

4

4 回答 4

3

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

于 2015-07-20T22:48:22.927 回答
1
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {      
    String allOutput = "";                                
    try {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec("cmd /c powershell C:/hello1.ps1");
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        BufferedReader outReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        while ((line = errorReader.readLine()) != null) {
            allOutput += "\n" + line;
        }
        while ((line = outReader.readLine()) != null) {
            allOutput += "\n" + line;
        }
        int retVal = proc.waitFor();
    } catch (IOException ex) {
        Logger.getLogger(BatchFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
    outputTextArea.setText(allOutput);
}
  • 使用 CMD.EXE /c 正确形成命令行
  • 检查错误流
  • 使用 Process.waitFor() 阅读 Process 类的 java-docs。
  • 无需关闭 OutputStream,因为您从不使用它并且程序不应该期望用户输入(java 切换输入和输出的名称很烦人)

注意上面的代码未经测试,因此可能存在语法错误等。

于 2013-01-03T13:50:13.467 回答
0

这是我测试过的代码,请注意在完成后选择“破解”或关闭 STDIN。

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test
{
    private static boolean hack=false;

    public static void main(String[] args) throws IOException
    {
        Runtime rt = Runtime.getRuntime();

        String cmd[];

        if (hack)
            cmd=new String[]{"cmd","/c","C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe","-File","c:\\cygwin\\home\\jpyeron\\test.ps1", "<NUL"};
        else
            cmd=new String[]{"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe","-File","c:\\cygwin\\home\\jpyeron\\test.ps1"};

        final Process p = rt.exec(cmd);

        Thread stdout = new Thread()
        {
            public void run() 
            {
                InputStream out = p.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(out)); 
                String line = null; 
                try
                {
                    while ((line = in.readLine()) != null) 
                    { 
                        System.out.println(line); 
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }              
            };
        };
        stdout.start();

        Thread stderr = new Thread()
        {
            public void run() 
            {
                InputStream err = p.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(err)); 
                String line = null; 
                try
                {
                    while ((line = in.readLine()) != null) 
                    { 
                        System.out.println(line); 
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }                
            };
        };
        stderr.start();

        if (hack)
            ;
        else
            p.getOutputStream().close();
    }
}
于 2015-04-15T00:59:39.320 回答
0

这对我有帮助:如果没有错误,请不要阅读 InputStream。例如

private void takeAction () throws IOException, InterruptedException
{
    String action = getAction (); // A powershell-Command
    Process p = Runtime.getRuntime ().exec ( action );

    InputStream is = p.getErrorStream ();
    if ( 0 < is.available () )
    {
        BufferedReader br = new BufferedReader (
                new InputStreamReader ( is ) );
        String err = br.readLine ();
        while ( null != err )
        {
            System.out.println ( "takeAction() " + err );
            err = br.readLine ();
        }
        p.getOutputStream ().close ();
    }
}
于 2016-03-04T12:33:17.927 回答