代码之家  ›  专栏  ›  技术社区  ›  soc Bhuwan Tripathi

如何从Java读取命令行输出(通过运行时.getRuntime().执行(…)

  •  0
  • soc Bhuwan Tripathi  · 技术社区  · 16 年前

    GUI具有 JTextArea resultTextArea JTextField statusField . 这是Dialog类中的代码:

    public void checkForSymLinks(File... dirs) {
        for (File dir : dirs) {
            try {
                Process p = Runtime.getRuntime().exec("find -type l", null, dir);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(p.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    resultTextArea.append(line);
                }
            } catch (IOException ex) {
                Logger.getLogger(SymbolicLinkSearchResultDialog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        statusField.setText("SymLinks found! // FIXME");
    }
    

    我试着换了 Process p = Runtime.getRuntime().exec("find -type l", null, dir); 签署人:

    ProcessBuilder pb = new ProcessBuilder("find -type l");
    pb.directory(dir).redirectErrorStream(true);
    Process p = pb.start(); 
    

    但这没有帮助。

    resultTextArea

    我得到了以下线索 对话框:

    java.io.IOException: Cannot run program "find -type l" (in directory "/home/johndoe/Desktop/test"): error=2, No such file or directory
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1024)
    

    我已经试过了 /usr/bin/find type -l 知道我做错了什么吗?

    PS:操作系统是Linux。

    def symLinkCheck(dirs: Array[File]) = {                              
      dirs.foreach{ dir =>                                                        
        val p = Runtime.getRuntime().exec("find -type l", null, dir)                    
        val in = new BufferedReader(new InputStreamReader(p.getInputStream)) 
        var line: String = null
        while({line = in.readLine; line} != null){
          println(line)
        }
      }
    }
    

    我在Scala中尝试了这段代码,它毫无问题地工作了。我真的不确定我的问题是否与挥杆有关?

    编辑:这个问题肯定与Swing有关。

    如果我以前调用过这个方法 theGUI.setVisible(true) 它起作用了,但之后就不行了。

    我已经试过了 SingUtilities.invokeLater 但那没用。

    3 回复  |  直到 16 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    你不能说你在用哪个操作系统。假设你 find 命令语法正确(在Mac OSX上不正确),我认为您应该:

    1. 同时 以避免阻塞行为。看到了吗 this SO answer 更多细节
    2. 通过收集派生进程的退出代码 Process.waitFor()
        2
  •  0
  •   Community Mohan Dere    9 年前

    不用运行Unix命令来查找符号链接,您可以在Java中通过比较 File.getCanonicalPath() File.getAbsolutePath() .

    更多详细信息请参见 this

        3
  •  0
  •   soc Bhuwan Tripathi    16 年前

    我发现了问题:在构造GUI之后,没有从事件调度线程调用该方法。