File I/O

Last week, we began to learn about the input and output of file. Before this topic, the information stored temporarily in the program will disappear as we close the program. However, now we can read from and write to files to get or store information. In this blog, I will explain classes and methods related to File I/O topic, and I will share a mini project I made using what I have learned about file I/O.

Stream Objects

A stream is an object that enables data to flow from the program to file or to I/O devices. When the data flow from the program to the file, the stream object is an output stream, as we write to the file. Contrasty, as data flow from the file to the program, the stream is an input stream.

Actually, we have already made use of input and output stream, when we use the following codes:

System.out.print("PrintToTheScreen");
Scanner input = new Scanner(System.in);

Text Files

Since we are reading and editing files, we should clarify that what we called “files” are usually text files. Different from binary files, which can be understand by computers, data in text files are encoded with ASCII coding scheme.

Dealing with text files, we need to import classes from java.io. As these codes show:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.FileNotFoundException;

Not only do we need the input and output stream classes, but also we need PrintWriter class to write to files.

The last line is used to deal with possible errors. We can use try catch to catch the error and send an error message.

try{
    inputStream = new Scanner(new FileInputStream("../example.txt"));
} catch(FileNotFoundException e){
    System.out.println("Failed to find the file.");
    System.exit(0);
}

This process is necessary for the program to run. The picture below shows what will happen if we do not deal with this possible error.

Picture1.png

Input Stream and Scanner

As this picture shows, we need to put the Scanner method in the try catch block. I have learned Scanner before, but we only used System.in, which is to get data from the keyboard. This time, we use the inputStream as the argument of the creation of the Scanner object. In side the parenthesis next to “Scanner,” we create a new file input stream. We put the name of the file there. The “../” means that the “example.txt” is located in the parent folder. If we use only “example.txt”, it will be in the same folder as the program.

Similar to what we have learned about Scanner, we can use methods like “.hasNext(), inputStream.next(), inputStream.nextLine(), inputStream.nextInt()”, etc. Every time we use .next…(), the Scanner will keep on searching, like a pointer, and it will never come back.

PrintWriter

For writing to files, we use FileOutputStream class as well as PrintWriter class which is used to write transmit data to the outputStream and to the file.

If we want to write to a txt file named “example” in the same folder of the program, we can use the following codes:

outputStream = new PrintWriter(new FileOutputStream("example.txt"));

This line is in the try catch block, before it, we need to declared the variable Output stream:

PrintWriter outputStream = null;

Then, we can write text to the file. Here is an example:

Picture3

This is quite similar to the System.out.print() method. We just need to change the former part to the PrintWriter object.

However, there might be a problem using the previous codes. If there is already a file named “example.txt,” this program will create a new file and replace the existing one, so the data in the original file will be deleted. If we want to append to a file, we can add a boolean argument into the parenthesis after “FileOutputStream”. Here’s the code:

Picture4

We put a another argument, “true,” after the file name, we can append to the file.

It’s important to note that after we finished using the input or output stream, we should close them, in another word, we clear the data stored temporarily in the streams. We use these codes (the two objects are created before):

 outputStream.close();
 inputStream.close();

Mini Project – Popular Names

After we learned file I/O topic, we did a mini project. That is, to write a program that can show the inputted name’s rank (according to popularity) and the number of people who are using the name. We are provided two files: One includes the boy names in the order of popularity and the number of people using them; the other is for girl names.

To create this program, I started using array, scanner, and input stream to store all the information in these two files.

4

Also, I used while loop and a int to access all the lines in the two files and write them to the array.

Then, I let the user to input the name, and then I used toLowerCase() method to make the problem more usable. I used subString() method to differentiate the names and the numbers. Then, I output them in a way that make sense. Also, I used a boolean variable to check if the name is found.

5

Here is the result:

3

This project shows my understanding and skill about file I/O. As what I said in the last post, I will continue on the Library project and implement file I/O. I believe the library project will be more easy to use after I used file I/O.

Leave a comment

Website Built with WordPress.com.

Up ↑