File reading/writing.
Reading an integer from a file data.txt

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

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

    public static void main (String [] args) throws IOException {
	// Create a buffered reader
	// to read from the file data.txt
	BufferedReader in = new BufferedReader(
			new FileReader("data.txt"));
	// string for storing a line of input
	String line;

	// Read one integer
	// prompt the user:
        System.out.print("Please enter an integer: ");
	// read a line of input:
	line = in.readLine();
	// check what the input is:
	System.out.println("The input is: " + line);
	// extract the integer from the entered data:
	int n = Integer.parseInt(line);
	// print out the value of n:
	System.out.println("n = " + n);

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

	// closing a file
	in.close();
    }

}

Writing into a file:

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

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

    public static void main (String [] args) throws IOException {
	// Create a buffered reader
	// to read from the file data.txt
	BufferedReader in = new BufferedReader(
			new FileReader("data.txt"));
	// string for storing a line of input
	String line;

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

	// read a line of input:
	line = in.readLine();
	// check what the input is:
	out.println("The input is: " + line);
	// extract the integer from the entered data:
	int n = Integer.parseInt(line);
	// print out the value of n:
	out.println("n = " + n);

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

	in.close();
	out.close();
    }

}

This is an example from CSci 2101 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.