簡體   English   中英

Java Runtime.exec() 程序不會輸出到文件

[英]Java Runtime.exec() program won't output to file

我有一個程序,它接受一個文件作為輸入並生成一個 xml 文件作為輸出。 當我從命令行調用它時,它工作得很好。 我嘗試使用以下代碼從 Java 程序中調用它。

    try
    {
        Process proc = Runtime.getRuntime().exec(c);

        try
        {
            proc.waitFor();
        }
        catch(InterruptedException e)
        {
            System.out.println("Command failed");
        }
    }
    catch(IOException e)
    {
        System.out.println("Command failed");
        e.printStackTrace();
    }

該程序似乎運行良好,因為它創建了一個 xml 文件; 但是,當我打開 xml 文件時它是空的。 我在我的 Java 程序中沒有遇到任何異常,所以我對問題可能是什么感到困惑。 為什么命令行程序可以正常工作,但是從 Java 調用時不會向它創建的文件輸出任何內容。 我在想也許這是某種權限的事情。 我嘗試以 sudo 運行程序(我使用的是 Linux),但無濟於事。 這個問題似乎不是我能在網上找到答案的任何東西。 希望這里有人能告訴我發生了什么。 :)

從您的流程中獲取輸出和錯誤流並閱讀它們以查看發生了什么。 這應該告訴你你的命令有什么問題。

例如:

try {
    final Process proc = Runtime.getRuntime().exec("dir");

    try {
        proc.waitFor();
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }

    final BufferedReader outputReader = new BufferedReader(new InputStreamReader(proc
            .getInputStream()));
    final BufferedReader errorReader = new BufferedReader(new InputStreamReader(proc
            .getErrorStream()));

    String line;

    while ((line = outputReader.readLine()) != null) {
        System.out.println(line);
    }

    while ((line = errorReader.readLine()) != null) {
        System.err.println(line);
    }
} catch (final IOException e) {
    e.printStackTrace();
}

如果任何一個流中都沒有輸出,那么接下來我將檢查外部程序和發送來執行它的命令。

對我來說,我寫了一個 jar 文件來輸出一個文件,然后在另一個 java 程序的命令行中運行它。 事實證明,我的 jar 文件中有一個基本檢查,我忘記了輸入字符串中的字符數(我的錯)。 如果字符數小於 8,則沒有輸出文件。 如果字符數大於 8,則使用以下代碼可以毫無問題地輸出輸出文件:

    String cmdStr = "java -jar somejar.jar /home/username/outputdir 000000001";
    try
    {
        Runtime.getRuntime().exec(cmdStr);
        Runtime.getRuntime().runFinalization();
        Runtime.getRuntime().freeMemory();
        log.info("Done");
    }
    catch (IOException e)
    {
        log.error(System.err);
    }

不確定我是否真的需要這里的一切,但是,嘿,它有效。 注意:在我的情況下似乎不需要等待。

您是否嘗試從 Java 外部啟動該進程?

在等待進程終止之前,必須處理進程輸入(實際上是進程的輸出!)和錯誤流。 這應該會更好

     try 
     {
         Process proc = Runtime.getRuntime().exec("anycomand");

         BufferedReader outSt = new BufferedReader(new InputStreamReader(proc.getInputStream()));
         BufferedReader errSt = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

         String line;

         while ((line = outSt.readLine()) != null) 
         {
             System.out.println(line);
         }

         while ((line = errSt.readLine()) != null) 
         {
             System.err.println(line);
         }

         proc.waitFor();

     } 
     catch (final IOException e) 
     {
         e.printStackTrace();
     }
     

但是為了更好地理解 Runtime exec 的工作原理,值得閱讀經典文章

當 Runtime.exec() 不會

它提供了有用的示例代碼(比上面的更好!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM