Prev Next

Input & Output

The Java library provides a rich set of ways to work with files. In this section we will restrict our attention to reading from console, reading from a file and writing to a file. You are request to refer to plenty of resources available on the web and the library to choose appropriate classes.

Reading input from console

While there are several ways to read a file from terminal (or input file), the simplest and the most common way is to use Scanner class. In this page we will cover some basic methods of this class for reading input interactively from console.

The Scanner class is a simple text scanner which can parse input that are of primitive types and strings. A Scanner typically breaks its input into tokens using a delimiter pattern (regular expression). In the absence of any pattern, it matches whitespace by default. The resulting tokens may then be converted into values of different types using the various next methods.

Scanner class is part of java.util package. In order to use Scanner one has to include the following import statement at the top of the program.

import java.util.Scanner;

public class ReadConsole {

  public static void main (String[] args)  {
    
    Scanner scanner = new Scanner(System.in); // create a Scanner instance

    System.out.print("Enter a string: ");	// prompt for a String
    String varString = scanner.next();		// read the string

    System.out.print("Enter an int: ");	// prompt for an integer
    int varInt = scanner.nextInt();		// read an integer

    System.out.print("Enter a float: ");	// prompt for an float
    int varFloat = scanner.nextFloat();		// read a float

    System.out.println("varString, varInt, varFloat = " 
    					+ varString + "\t"
    					+ varInt + "\t"
    					+ varFloat);
    
    if (scanner.hasNext())				// Check if input exists
      String line = scanner.nextLine();	// If so, read the entire next line

    while (scanner.hasNext())        // As long as input exists
      String line = scanner.nextLine(); // read the next line
  }
}

Run this program at the command prompt and check its working.

The code scanner.nextInt() is equivalent to Integer.parseInt(scanner.next()).

What happens when you call scanner.nextInt() and provide a string as command instead of an integer? You will get java.util.InputMismatchException. Try and check it out!

Scanner class supports several more features. Please refer to Java docs and plenty of other resources in the web.

Reading from a file

The Scanner class can also be used to read input from a text file.
import java.io.File;
import java.util.Scanner;

public class ReadFile {

  public static void main (String[] args)  {

  	try {
  		File file = new File("input.txt");	// Create File instance 
    	Scanner scanner = new Scanner(file); // create Scanner instance

    	// Now call next*() methods to read tokens in the usual way

    	// Your code to process them

    	file.close();	// Close the file
    }
    catch (IOException ioe) {
    	// Deal with it your way
    }
  }
}

Note that you have to include the code in try...catch block. Most of the functions in java.io package throw checked exceptions such as IOException, FileNotFoundException, etc which have to be caught and handled.

Writing to file

The FileWriter class can be used to write to a file. The following code shows a simple example.

import java.io.File;
import java.io.FileWriter;

public class WriteFile {

  public static void main(String[] args) {

  	try {
  	  File file = new File("output.txt"); // Create File instance

  	  file.createNewFile();	// Create output.txt in current directory

  	  FileWriter writer = new FileWriter(file); // FileWriter instance

  	  writer.write("Learning to do IO in Java"); // Write to the file

  	  writer.close();	// Close writer
  	} 
  	catch (Exception e) {
  		// Deal with it your way
  	}
  }
}

Exercise

1. Implement a driver class which reads 2 points from the terminal, computes the distance between them and outputs the result.

Input:
12 -3
-7 -6

2. Implement another driver to read from 'input.txt' file instead of terminal, computes their sum and writes the result to 'output.txt'.

A Final note

What we have covered here is the most basic way of reading from and writing to files. Java library offers plethora of simple to sophisticate ways to access and manipulate files and their properties. For a full-fledged information of them please refer to java.io, java.nio and java.nio2 packages in Java docs site.

For a good overview Java File I/O.