Java - How to read user input or file input redirection

By xngo on February 27, 2019

In Java, if you want your program to be able to read data from input redirection, then you need to read from System.in.

YOUR_PROGRAM_CMD < sometTextFile.txt

The following program will read input from users or from file, i.e YOUR_PROGRAM_CMD < someTextFile.txt. Then, it will print back what the users type or print content of file that is being redirected.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
 
public class InputRedirection
{
 
  public static void main(String[] args)
  {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
 
    try
    {
      while( (line = reader.readLine()) != null )
      {
        if(line.length()==0)// Quit if user presses Enter. 
          System.exit(0);
 
        System.out.println(line);
      }
    }
    catch(IOException ex)
    {
      ex.printStackTrace();
    }
  }
 
}

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.