虽然,不退出

时间:2014-10-19 18:17:40

标签: java while-loop

我正在处理一个项目并且遇到问题,我发布这个程序与我工作的类似。

问题是:当程序执行其功能时进入,然后挂起并且不退出。

我已经尝试了一切。任何人都可以提出任何建议吗?

public class CommandZ {

    private static String Command;
    private static Scanner scan;


    public static void main(String[] args) {        
        scan = new Scanner(System.in);

            System.out.println("Shell: ");
            Command = scan.nextLine();

            ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-Command", Command);
            Process p;
            try {
                p = pb.start();
            } catch (IOException e) {
                System.out.println("Failed to start powershell");
                return;
            }

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            System.out.println("Begin!");
            try {
                //PROBLEM
                while((line = bufferedReader.readLine()) != null){
                    System.out.println(line);                                       
                }
            } catch (IOException e) {
                System.out.println("Failed to read line");
                return;
            }

            System.out.println("Exit");

        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以尝试两件事。首先,您可以从单独的线程中读取衍生进程的输出。如果您这样做,请务必将bufferedReader设置为final

Thread t = new Thread(new Runnable(){
    public void run(){
        // might need to try/catch round this
        while((line = bufferedReader.readLine()) != null){
                System.out.println(line);                                       
        }
    }
}).start();

然后就在你的计划结束之前:

t.join();

确保该线程完成其工作。

另一个选项是使用ProcessBuilder.inheritIO()将该进程的输出重定向到Java程序的输出:

Process proc = new ProcessBuilder().inheritIO().command("powershell.exe", "-Command", Command).start();

答案 1 :(得分:0)

在您的代码中,您应该更改的唯一内容是您定义行的位置。结果会是这样的:

  //Solution 
      string line = bufferedReader.readLine();
      if(line ==null){
        System.out.println("Empty document");
      }else{
        while((line!= null){
           System.out.println(line);
           line=bufferedReader.readLine();
     }

如果你有Java 8,我将引荐你参考这个文档:http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-

希望我的回答可以帮助你!

相关问题