Close

Java Command Line - Sending Command Input To Java via command line pipe

[Updated: Dec 27, 2018, Created: Dec 27, 2018]

Java Command Line 

This example shows how to redirect a command output to a Java Program as input. For example:

externalCommand | myJavaProgram

The Java Program needs to get the input via System.in.

Following example just echoes back whatever input it receives:

package com.logicbig.example;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExampleMain {
  public static void main(String[] args) {
      System.out.println("----- ExampleMain started -------");
      try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
          String line = null;
          while (true) {
              if ((line = reader.readLine()) != null) {
                  System.out.println("echo>> " + line);
              } else {
                  //input finishes
                  break;
              }
          }
      } catch (Exception e) {
          System.err.println(e);
      }
  }
}

Compile above class:

D:\java-pipe-input>mvn -q compile

Create a batch file to run the main class:

myJavaProgram.bat

@echo off
java -classpath target\classes com.logicbig.example.ExampleMain

Output

D:\java-pipe-input>dir d:\test | myJavaProgram
----- ExampleMain started -------
echo>> Volume in drive D is Data
echo>> Volume Serial Number is 68F9-EDFA
echo>>
echo>> Directory of d:\test
echo>>
echo>> 05/12/2017 01:32 AM <DIR> .
echo>> 05/12/2017 01:32 AM <DIR> ..
echo>> 05/12/2017 01:35 AM 2,508 logging.properties
echo>> 05/09/2017 09:25 AM 19 one.txt
echo>> 05/03/2017 10:20 PM <DIR> testDir1
echo>> 05/03/2017 10:21 PM <DIR> testDir2
echo>> 04/28/2017 09:00 AM 0 two.txt
echo>> 3 File(s) 2,527 bytes
echo>> 4 Dir(s) 20,635,299,840 bytes free
D:\java-pipe-input>ps -s | myJavaProgram
----- ExampleMain started -------
echo>> PID TTY STIME COMMAND
echo>> 22316 pty0 12:00:59 /d/Program Files/JetBrains/IntelliJ IDEA Community Edition 2018.2.5/bin/idea64
echo>> 36784 cons2 16:16:05 /usr/bin/ps
echo>> 22608 pty0 12:00:46 /usr/bin/bash
echo>> 10356 ? 12:00:45 /usr/bin/mintty
D:\java-pipe-input>dir c:\ | findstr "Program*" | myJavaProgram
----- ExampleMain started -------
echo>> 12/18/2018 07:18 PM <DIR> Program Files
echo>> 12/19/2018 10:20 AM <DIR> Program Files (x86)

Example Project

Dependencies and Technologies Used:

  • JDK 11
  • Maven 3.5.4

Piping input to Java Select All Download
  • java-pipe-input
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java

    See Also