Simple Text File I/O

Previously, we have gotten input from the keyboard and sent output to the screen. It is often convenient (or necessary!) to get input from files on the disk or to save output from the program to files on a disk.

Three basic file operations:
1) Open the file.
2) Read from the file or Write to the file.
3) Close the file.
File I/O (input/output) may be described as sequential or random. With sequential access, values stored in the file are read in order. With random access, you can selectively read values from the file in any order you specify. We will use sequential access since it is simpler.

Keep in mind that Java has many ways to read in files depending on the type of file and how you want to treat it. We will read from and write to text files using applications, because it is relatively simple to do this.

As we have discussed previously, working with I/O can cause exceptions to be thrown. We will see several types of exceptions in the programs we will be examining.


Declaring the file object and connecting it to an input stream:

//read from keyboard
	BufferedReader in =new BufferedReader
        (new InputStreamReader(System.in)); //keyboard IO

//read from input file
	BufferedReader in= new BufferedReader
	(new FileReader("infile.dat"));    //where infile.dat exists

//write to output file
 	PrintWriter out= new PrintWriter
        (new FileWriter("outfile.dat")); //outfile.dat is created
Read or write to the file in the usual way:
	string word=in.ReadLine(); //reads in a word from the file
	int x=5; 
	out.println(x);//writes 5 to the file

Close the file when you are done with it:
	in.close();
	out.close();

Click here to return to IT 108 web page


Copyright © 1999-2002 All Rights Reserved