next up previous contents
Next: Output to a file Up: 5 More advanced input Previous: Formatting output   Contents

Input from a file

As with reading input from the keyboard, you will need to include some particular code near the beginning of your source file in order to use the methods for reading input from a file.

import java.io.*;

public class InputDemo
{
    public static void main(String[] args) throws IOException,
                                                  FileNotFoundException
    {

This is the same as for keyboard input but with the addition of FileNotFoundException. This is the exception that will be written to your screen if the input file you specify does not exist.

To open your file (the example here is named `file1.in') from which the input should be read:

// Open file to read input from
BufferedReader br = new BufferedReader(
                     new InputStreamReader(
                      new FileInputStream("file1.in")));

As with keyboard input you are not yet expected to understand how this code works, it is enough to be able to copy and make use of it. The indentation is not necessary but again just makes things clearer. This code need only be included once in your program. Once the file is open, a line of the file is read using:

temp = br.readLine();  // where temp is a String you should declare first

Every time you use this command the next unread line of the file will be placed into the string temp. As with keyboard input, one of Double.parseDouble(temp), Int.parseInt(temp), etc. must be used to convert the string temp into the number type if required.

To read a file, line by line, until the end of the file is reached, you can do something like this (assuming temp and b are declared as above):

    while ((temp = br.readLine()) != null)
    {
        System.out.println("read line: " + temp);
    }


next up previous contents
Next: Output to a file Up: 5 More advanced input Previous: Formatting output   Contents
RHUL Dept. of Physics