2016-09-20 71 views
0

我有一個程序,允許用戶按下按鈕,然後運行命令行語句,用戶可以看到輸出。如何在Java中停止命令行過程

我現在想知道在結束之前是否可以停止命令。 當我正常運行命令提示符時,我知道命令「ctrl + c」,但是,我不確定如何在java程序中執行此操作。

runButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent r) { 
     JFrame runFrame = new JFrame("Running process..."); 
     runFrame.setSize(500, 400); 
     runFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); 
     runFrame.setLayout(null); 
     JButton somethingButton = new JButton("Stop"); 
     JButton closeButton = new JButton("Close"); 
     somethingButton.setBounds(65, 290, 105, 25); 
     closeButton.setBounds(335, 290, 105, 25); 
     JTextArea run = new JTextArea(); 
     JScrollPane runSP = new JScrollPane(run); 
     runSP.setBounds(65, 50, 375, 200); 
     run.setLineWrap(true); 
     run.setWrapStyleWord(true); 
     run.setEditable(false); 
     runFrame.add(runSP); 
     runFrame.add(somethingButton); 
     runFrame.add(closeButton); 
     runFrame.setVisible(true); 
     //Start of creating of command line stuff 
     Runtime runtime = Runtime.getRuntime(); 
     Process process = null; 
     try { 
      process = runtime.exec("ping riot.de"); 
     } catch (IOException e1) { 
      System.err.print("Error: " + e1); 
      e1.printStackTrace(); 
     } 
     try { 
      StringBuilder sb = new StringBuilder(); 
      BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); 
      String line; 
      while ((line = br.readLine()) != null) { 
       sb.append(line); 
       sb.append("\n"); 
      } 
      run.setText(sb.toString()); 
     } catch (IOException e) { 
      System.err.println("Error: " + e); 
     } 

     closeButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent c) { 
       runFrame.dispose(); 
      } 
     }); 

     somethingButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent c) { 
       //CODE TO STOP HERE 
      } 
     }); 
    } 
}); 
+1

System.exit(0);不適合你? – Stultuske

+0

@Stultuske我不想關閉整個程序。這是一個小片段。 – Plumel

+0

因此......您想「停止」應用程序,而不是「停止」應用程序?你的意思是打斷一個線程? – Stultuske

回答

3

嘗試使用所提到的代碼來destry過程process.destroy();

+0

謝謝,我會看看 – Plumel

+0

我得到這個錯誤:在一個封閉的範圍內定義的本地變量進程必須是最終的或有效的最終 – Plumel

+0

你可以把錯誤stacktrace。 – mhasan