#author("2017-07-08T21:08:55+09:00","","")
#navi(../)
* パイプ(|)によるデータの受取方法 [#tba41f9f]
Linux(*BSD)などのシェルでコマンドとコマンド間でデータを渡すときにパイプ(|)を使用しデータのやりとりをしますよね。~
Javaで作成したプログラムにパイプ経由でデータを渡すサンプルソースと実行例を記します。

#contents
* system.inからデータを取得する [#kf3b452d]
以下のサンプルソースの通り、system.inにデータがあるか(パイプによるデータ受け渡しがあるか)をチェックし~
その後、InputStreamReader, BufferedReaderをつかって一行ずつ読み込んでいます。~
本サンプルソースでは、読み込んだ行の先頭に行番号を%04dという形で表示しています。~
尚、文字コードはLinux(Ubuntu)にて動作確認を行ったので、UTF-8を指定しています。

#ref(PipeIn.java)
 class PipeIn {
     public static void main(String[] args) {
         try {
             if (System.in.available() != 0) {
                 InputStreamReader in = new InputStreamReader(System.in, "UTF-8");
                 BufferedReader b = new BufferedReader(in);
                 String l;
                 int i = 1;
                 while (null != (l = b.readLine())) {
                     System.out.printf("%04d: %s\n", i, l);
                     i++;
                  }
             } else {
                 System.out.println("No input by the pipe.");
             }
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 }

* 実行例 [#pb4f61ae]
以下に本サンプルソースのコンパイルおよび実行結果を記します。

- Linux(*BSD)コマンドのprintfコマンドを利用しhello\nworldを今回作成したサンプルの入力とした時の実行例です。
 $ printf "hello\nworld" | java PipeIn 
 0001: hello
 0002: world

- 本サンプルソースをcatで渡し、headコマンドで先頭から10行表示させています。
 $ cat PipeIn.java | java PipeIn | head -10
 0001: import java.io.*;
 0002: 
 0003: class PipeIn {
 0004:     public static void main(String[] args) {
 0005:         try {
 0006:             if (System.in.available() != 0) {
 0007:                 InputStreamReader in = new InputStreamReader(System.in, "UTF-8");
 0008:                 BufferedReader b = new BufferedReader(in);
 0009:                 String l;
 0010:                 int i = 1;

- パイプによる入力がない場合。
 $ java PipeIn 
 No input by the pipe.

使用したJDKバージョン
 $ java -version; javac -version
 openjdk version "9-internal"
 OpenJDK Runtime Environment (build 9-internal+0-2016-04-14-195526.buildd.src)
 OpenJDK Server VM (build 9-internal+0-2016-04-14-195526.buildd.src, mixed mode)
 javac 1.8.0_131

以上、Javaでパイプによる入力(STDIN)を扱うサンプルソースでした。


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS