Reading String input from the Keyboard or a file
If you are interested in reading strings from the keyboard or from a file, here is an example that can help. This information was obtained from the following:

This sample has both examples - one of getting string input from a user and another which gets input from a file named my_input.dat. They are combined so you can see the differences in how they are implemented.




public class test {

public static void main( String Args[] )


String mymessage = "";

String mymessage2 = "";

try {

///// accept string input from the keyboard and print it out /////

System.out.print("Enter a message you want: ");

BufferedReader KeyboardInput = new BufferedReader(new InputStreamReader(;

mymessage = KeyboardInput.readLine();

System.out.println("The string you entered is: " + mymessage);


///// read a file from disk and print out all the lines from it /////

BufferedReader FileInput = new BufferedReader(new FileReader("my_input.dat"));

mymessage2 = FileInput.readLine();

while (mymessage2 != null)


System.out.println("file: " + mymessage2);

mymessage2 = FileInput.readLine();



catch (IOException ex) {

System.out.print("IO exception occurred!!!");





} // end of method main


} // end of class


public class InputStreamReader
extends Reader

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and translates them into characters according to a specified character encoding. The encoding that it uses may be specified by name, or the platform's default encoding may be accepted.

Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. For top efficiency, consider wrapping an InputStreamReader within a BufferedReader; for example,

 BufferedReader in
   = new BufferedReader(new InputStreamReader(;