Reading data from a file with the name supplied by the user:

import java.awt.*;
// Need this import for reading data:
import java.io.*;
import java.util.*;

// reading data in a Java application
public class FileReadTest {

    public static void main (String [] args) throws IOException {
	// read the file name from standard input
	BufferedReader nameinput = new BufferedReader(
			new InputStreamReader(System.in));
	System.out.println("Please enter a file name: ");
	String filename = nameinput.readLine();
	
	BufferedReader in;

	// open the file for writing:
	PrintWriter out = new PrintWriter(new BufferedWriter(
			           new FileWriter("out.txt")));

	// get timestamp:
	Date tstamp = Calendar.getInstance().getTime();
	out.println(tstamp.getHours() + ":" + tstamp.getMinutes() + 
		    ":" + tstamp.getSeconds());

	int n = 0; // need to initialize
	try {
	    in = new BufferedReader(
			new FileReader(filename));
	    // read a line of input
	    // must use "in" within the "try" because it
	    // may be undefined outside
	    String line;
	    line = in.readLine();
	    // check what the input is:
	    out.println("The input is: " + line);
	    // extract the integer from the entered data:
	    n = Integer.parseInt(line);
	    // print out the value of n:
	    in.close();    
	    
	} catch (IOException e) {
	    System.out.println("There was a problem opening the file " + 
			       filename);
	    System.out.println(e.getMessage());
	    System.exit(0);
	}

	// output n:
	out.println("n = " + n);

	// increment n by 1
	n = n + 1;
	// print out the result:
	out.println("n = " + n);

	out.close();
    }

}

This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.