Monday Mar 02, 2009

Java Code for Reading Standard Input

This weekend I needed to write a Java application that can read data from Standard Input.  The application runs as a command line application.  I searched the web for some examples of reading data from Standard Input, but I found the easiest way of doing this was to use the Apache Commons IO Library.  This library simplifies the task of reading data from an input stream and converting that data to a String.  This is exactly what I needed to make my life a little easier.  Here is a simple block of code that does the input and conversion:

String body = null; 
// Read the input from stdin
InputStream in = System.in;
try {
    body = IOUtils.toString(System.in); 
} catch (IOException ioe) {
    System.err.println("IO error trying to read message!");
    System.exit(1);
} finally {
    IOUtils.closeQuietly(in);

That's about as simple as it gets.  Now I can use this program to process data presented as Standard Input on the command line.  For example:

java -cp MyStdInReader.Main < somefile.txt


 

About

user12622652

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today