The programs we've written so far, except "Array ," the data are require to be re-enter each time we re-run the program. This is because the data is stored in RAM, and it will disappear once the program stops running. To retrieve the data, a program must have a way of saving the data, hence Java API provides several classes that we can use for writing data to a file and reading data from a file. To write data to a file (using java file Methodology), we can use the PrintWriter class, and optionally, the FileWriter class. To read data from a file, we can use the Scanner class and the File class.
In general, there are two types of files: text and binary. A text file contains data that has been encoded as text, using a scheme such as Unicode. Even the file contains numbers, those numbers are stored in the file as a series of characters, in other word they are stored as " Strings ." As a result, the file may be opened and viewed in a text editor such as Notepad. A binary file contains data that has not been converted to text. As a result, we can not view the contents of a binary file with a text editor. As of this chapter, we will only discuss how to open and view text files.
The Java API provides a number of class that we will use to work with java files. Hence, in order to use these classes, we will need to import the java I/O.
import java.io.*;
The statement needs to place on the top of the program before we can open/create any text files.
Using the Java PrintWriter class to write data to a file
To write data to a file, we will need to create an instance of the PrintWriter class. The PrintWriter class allows us to open a file for writing. We can write data to the file using the same print and println methods that we've been using to display data on the screen. In order for us to open a text file for writing, the text file that we create must be in the same directory as the program. For example, all the programs I've written so far they are locate in "C:\java\", so the text file I create must be in "C:\java\". If the program and the text file are in a different directory, we wouldn't be able to open the text file.
Note: Whenever we open a file, we have to close the file.
Opening a file
PrintWriter pw = new PrintWriter("Name.txt");
The above statement creates an empty file called Name.txt and establish a connection between it, and the PrintWriter object is referenced by pw. The file will be created in the same directory or folder as the program. Thus, whenever we want to write data into the text file, we use the key word pw. In addition to that, we have to throw IOException, it's an exception handling, we have to put it right after public static void main(String[] args), or else we would get an error saying unreported excpetion has been caught. Here is a piece of code that will create a new text file, then writes data into the file.
// Opens the text file Name.txt, if it doesn't exists it will create a new one
PrintWriter pw = new PrintWriter("Name.txt");
// Writes Joe into the file
pw.println("Joe");
// Closes the file
pw.close();
Now lets observe a basic example
ClickHere to download FileIn.java
The above program does not append the names, which means whenever we run the program to re-enter names, it will replace the original names with the new one. In addition to that, it doesn't give the user much choices with the name of the file. Hence, we will see a program below that allows the user to create the name of the file and append names to a text file. Thus, it gives the user more options and choices. To append data to a file we would have to use the FileWriter class, hence we would have the following two statements:
FileWriter fwriter = new
FileWriter("Name.txt", true);
PrintWriter pw = new PrintWriter(fwriter);
This creates a PrintWriter object that can be used to write data to the file Name.txt, we set it to be true so that any data that is written to the file will be appended.
Java appending data to a File
ClickHere to download FileAppend.java
Reading Data from a File
Reading data from a file is very similar from writing data to a file. We need to have the two import statements, java.util.*; and java.io.*; where util.* is for the Scanner class and .io*; is for the input and output file class. In addition to that we still need to have throws IOExcpetion after main for throwing input/output exceptions. Here is an example on how to open a file:
File file = new File("MyName.txt");
Scanner input = new Scanner(file);
Here we created an instance of the File class, then it's used to represent a file. Notice here we passed the string "MyName.txt" to the constructor. This creates a file object that represent the file MyName.txt. Hence, whenever we want to read a line from the file we use the key word input. Lets see an example on how to read a single line from a file.
Here is an output of the program:
Enter the name of the file:
Name.txt
The first line in the file is:
jj
ClickHere to download ReadLine.java
Java reading until end of file
That only reads the first line, but what if we want to continue reading until we reach the end of the file. The Scanner class has a method named hasNext that can be used to determine whether the file has more data that can be read. If the end of the file has been reached and there is no more data to read, the hasNext method will end. Now lets observe an improve of our previous example:
Here is the output of the program:
Enter the name of the file:
Name.txt
jj
jo
hi
ClickHere to download DetectEndOfFile.java
Reading Primitive Values from a File
Recall, the Scanner class provides method for reading primitive values. These methods are named nextByte, nextDouble, nextInt, nextFloat, NextLong, nextShort. Reading the primitive values from a file is the same as reading String. Lets see a basic example:
Here is the output of the program:
Enter file name:
Number.txt
The sum of the number is 20
ClickHere to download FileNum.java
Checking for File's Existence
It's usually a good idea to make sure if a file exists before we try to open the file for input. Hence, the File class has the exists method which allows us to check if a file exists or not. Lets see an example on how to use the exists method.
ClickHere to download FileExist.java
File Exception Handling
ClickHere to download FileException.java
Notice, here we didn't put throws IOException after the main, instead we try to catch the Exception inside the main method.