2017-11-30 27 views
0

Javaアプリケーションでruntime.getruntime.execを使用しようとしています。Runtime.getRuntime.exec()エラーコード

かなり長い間、私は別のコマンドを実行しようとしていましたが、ファイルまたはディレクトリが存在しないことを意味するエラーコード2が続きました。テストするために、基本コマンドを渡してエラーコード1を取得しようとしました。なぜこれを取得していますか、エラーコード1は何を意味しますか?ここで

は私のコードです:ここでは

private String executeCommand(String command) { 
    logger.info("executing command : " + command); 
    String result = null; 
    try { 
     Runtime rt = Runtime.getRuntime(); 
     Process pr = rt.exec(command); 

     BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); 
     BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream())); 
     String line = null; 

     while ((line = input.readLine()) != null) { 
      result = result + line; 
     } 

     while ((line = stdError.readLine()) != null) { 
      result = result + line; 
     } 
     int exitVal = pr.waitFor(); 
     System.out.println("Exited with error code " + exitVal); 


    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (NumberFormatException e) { 
     e.printStackTrace(); 
    } catch (Throwable e) { 
     e.printStackTrace(); 

    } 
    logger.info("This is the result:" + result); 
    return result; 

は、私はそれを呼び出す方法です。ここで

String temp = executeCommand("cd $HOME/my-directory/my-subdirectory"); 

は私の出力です:

INFO : programname - executing command : cd $HOME/my-directory/my- 
     subdirectory 
Exited with error code 1 
INFO : programname - This is the result:null/usr/bin/cd[8]: $HOME/my- 
     directory/my-subdirectory: not found 
+0

ホーム変数を囲み、 'String temp = executeCommand(" cd $ {HOME}/my-directory/my-subdirectory ");' –

+0

変更を実行しないでください。さらに、コマンドラインでそれを単独で実行すると、このコマンドは完全に正常に動作します – iswg

+0

'String temp = executeCommand("/usr/bin/cd $ HOME/my-directory/my-subdirectory ");' –

答えて

0

Process pr = rt.exec("cmd /c "+command);

+0

私はこれをUNIXサーバーで実行しています。プログラム「cmd」を実行できません。 – iswg

1

Runtime.getRuntime().exec(command)を実行します。渡された文字列の最初のパラメータとして、exeファイルが必要です。 (cd, echo, etc...)のようなコマンドは、コマンドラインツールに固有であり、直接渡されたコマンドとしては機能しません。最初にコマンドラインツールを起動し、コマンドを引数として渡す必要があります。

// Invoke Command Line Tool (.exe is optional) (cmd for windows sh for Linux) 
// 1st argument indicates you want to run a command (/C for windows -c for Linux) 
// 2nd argument is the cmd line command to run (echo) 
Runtime.getRuntime().exec("cmd.exe /C echo helloworld"); 
Runtime.getRuntime().exec("sh -c echo helloworld"); 

別途注意してください。結果をnullではなく空の文字列に初期化する必要があります。それ以外の場合は、 "null"という単語が印刷前に付加されます。

+0

私はこれをUNIXサーバーで実行しています。ただ、プログラム "cmd.exe"を実行することはできません – iswg

+0

あなたはunixのためにcmdの代わりにshを使いたいと思っています – Steve

+0

私はshを使いましたが、私はまだ同じエラーコードを取得しています。変更されたのは、「見つからない」代わりに、「存在しない」ということです。しかし、このディレクトリは私がプログラムを実行しているので、確実に存在します。 – iswg