3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

BashスクリプトをJavaで実行してみよう

Last updated at Posted at 2019-03-11

#はじめに
JavaにおいてProcessbuilderだとかRuntimeでプロセスを作ってあげると、Linux上の挙動とは必ずしも同一でない振る舞いをすることがあります。
一時的に「bashスクリプト(シェルスクリプト)」をつくってあげて、それを実行してあげると、望み通りの挙動になるかもしれません。

#コード


public void executeCommands() throws IOException {

//一時ファイル作成
    File tempScript = createTempScript();

    try {
        //スクリプト実行
        ProcessBuilder pb = new ProcessBuilder("bash", tempScript.toString());

       //エラー出力
       try (BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
               System.out.println(buffer.lines().collect(Collectors.joining("\n")));
       }

      //標準出力
      try (BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
               System.out.println(buffer.lines().collect(Collectors.joining("\n")));
       }
        Process process = pb.start();
        process.waitFor();
    } finally {
        //一時ファイル削除
        tempScript.delete();
    }
}

public File createTempScript() throws IOException {
    //一時ファイル作成
    File tempScript = File.createTempFile("script", null);

    Writer streamWriter = new OutputStreamWriter(new FileOutputStream(
            tempScript));
    PrintWriter printWriter = new PrintWriter(streamWriter);

    //スクリプトを書いていく。
    printWriter.println("#!/bin/bash");
    printWriter.println("cd bin");
    printWriter.println("ls");

  //書き込み終了
    printWriter.close();

    return tempScript;
}

#参考(これのパクリ)
https://stackoverflow.com/questions/26830617/running-bash-commands-in-java

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?