In this IB Computer Science lesson you will be learning about:
Any program that processes a considerable amount of data has to read the data from a file (or several files).
There are essentially 2 types of data files:
Binary files
Text files
Files can be accessed using 2 types of methods
Random Access
Sequential Access
In this course we will only look at sequential access of text files
If you have a text file you can just drag and drop it into Netbeans, but you can also just create the file directly
Instead of Selecting a New Java Class or JFrame Form, select Other
Select Other and Choose Empty File
Name the file, choose the location.
When we wanted to access input data from the keyboard, we created a link to the System.in data stream using the class InputStreamReader.
When accessing files we are not going to access the System.in data stream, but we are going to treat the file itself as the data stream.
To create this link we must use a class called FileReader and link to the location of the text file on our computer.
A typical line to create this link to a text file named data1.txt would look as follows:
FileReader fileInStream = new FileReader (“data1.txt”);
TO MAKE THINGS AS EASY AS POSSIBLE RIGHT NOW I SUGGEST THAT YOU SAVE YOUR FILES IN THE SAME DIRECTORY AS YOUR .java FILE THAT YOU ARE CREATING TO AVOID HAVING TO SPECIFY THE PATH.
YOU MIGHT NEED TO ADD “src/file.txt” if it can’t find your file and your using the default package in NETBEANS
This line constructs an FileReader object and gives it the name fileInStream.
Now that the link is created you need a collection of methods to actually read in the data.
To make this task as simple as possible we will one again use a class called BufferedReader to read in the data from the input stream we just linked to.
A typical line would look something like this
BufferedReader fileInput = new BufferedReader (fileInStream);
This line creates a BufferedReader object named fileInput that links to the input stream object fileInStream created before. You have already used the BufferedReader Class before and it works the exact same way when reading in data from a file as it does when you read in data from the keyboard. You can use the readLine method to read in an entire line from the file as a String. If you are required to change that string to different data type you can use the same methods that you used during keyboard input to do this.
As with keyboard input we can combine all of this into one line
BufferedReader fileInput = new BufferedReader (new FileReader (“data1.txt”));
When you are finished reading in any data from a file it is important to close the stream link
fileInput.close ( );
In order to write programs using input data from a file it will be necessary to have some information about how the information is stored in the data file (are they numbers, letters, strings, are there more than one piece of information on each line, how many lines of data are there, etc)
We will start with the simplest situation in which there is one type of data in file (all integers, all strings, etc) and there is only 1 data entry per line on the file
Example 1:
We will write a program that asks the user to enter a person’s last name. The program then searches a text file (names.txt) that contains 20 different last names one per line. An appropriate message is outputted if that last name is found in the data file
You might notice that I forget to close the file when done in these examples 🙁
Example 2:
One good strategy when dealing with data of one type in a file is to read in all the values from the file into an array, then the values in the array can be manipulated according to the situation
The following program reads in data from a file named Numbers.txt that has 15 integer values and stores those numbers inside an array.
Example 3:
Another way to indicate how many lines of data are in a file are to use the first line to indicate how many lines or sets of data are stored in the file
The following program reads in data from a file called letters.txt with the first line of the file indicating how many lines of character data are stored after it. The program then stores the data inside a character array.
Example 4:
Sometimes you have no idea how much data is stored inside the data file, so one strategy you can use is to read in data until the value you read in is null, which means a blank line has occurred, which would generally mean the end of the file
The following program reads in a set of decimal numbers from a file called AddValues.txt, there are an unknown number of decimal values in the file. The sum of all the numbers is outputted to the screen at the end of the program.
In this example we are going to be calculating the BMI (Body Mass Index) of different people. A data file called BMI.txt exists that has 5 sets of data. Each set of data contains 3 lines. The first line states the person’s name, the second line indicates either METRIC or IMPERIAL measurements, the third line represent the person’s height, and the fourth line represents the person’s weight. The program will output a list that states each person’s name, their BMI, and their BMI category. Use 2 decimal places for the BMI.
Not only is it possible to read data in from external files, we can also write information to external files
There are essentially 2 options when writing data to external files
Once again if we want to write data to an external text file, you must open that text file using an output stream. To create this link we must use a class called FileWriter and link to the location of the text file on our computer. You must also indicate if you would like to perform a write or append operation to the open file
A typical line to create this link to a text file named data1.txt using the write option would look as follows:
FileWriter fileOutStream = new FileWriter (“data1.txt”, false);
A typical line to create this link to a text file named data1.txt using the append option would look as follows:
FileReader fileOutStream = new FileReader (“data1.txt”, true);
IF THE FILE DOESN’T EXIST WHEN YOU TRY TO CREATE THE OUTPUT STREAM IT WILL CREATE ONE FOR YOU
This line constructs an FileWriter object and gives it the name fileOutStream. Now that the link is created you need a collection of methods to actually output the data. To make this task as simple as possible we will use a class called PrintWriter to output the data to the output stream we just linked to.
A typical line would look something like this
PrintWriter fileOutput = new PrintWriter (fileOutStream);
This line creates a PrintWriter object named fileOutput that links to the input stream object fileOutStream created before. The PrintWriter class contains two methods that you have worked with before to deal with output and they work exactly the same as when you used them with the System.out stream. Basically you can just pretend you are outputting data to the screen, but instead of sending your output to the monitor its sends it to the data file
When you are finished reading in any data from a file it is important to close the stream link
fileOutput.close ( );
NO DATA GETS WRITTEN TO THE FILE UNTIL IT IS CLOSED!!!!
Example 1
Write a program that asks the user to input the length and width of 5 rectangles and the program then outputs the length, width, area, and perimeter to an external file named rectangle.txt. Write the information with only 2 decimal places only The program can open the file for a strict write only and can write the information with 1 piece of data per line
In all of the above examples we have been avoiding Exception Handling by adding the line throws IOException beside the main method. Ignoring IO exceptions doesn’t work nicely with the GUI builder.
You will need to use try – catch statements in order to use data files in a GUI
Example:
Here is an example of a GUI program that reads integer data from a text file called “in.txt” into an array, finds the maximum, minimum, average and writes that data to a separate file. There are an unknown amount of integers in the input file.
GUI DESIGN
Keep it simple, everything is just written inside the one button
There will only be one event, so all the code is performed in the action performed event for the single button. Here is the general pseudocode to make this work
Find the number of values in the file
Create the array and read the values in
Calculating the values
Write data to the file
1. Golf Tournament
Students compete in a virtual golf tournament. The tournaments participants were required to play 9 holes of golf and then submit their scores for each hole to the judge. Your job is to assist the judge by writing a computer program to add up all the scores for each player
The first line of the input file (GolfIN.txt) will contain an integer N, representing the number of participants in the tournament. Each subsequent line will contain the players first name followed by the scores for each of the 9 holes. All data is on a separate line.
The output file (GolfOUT.txt) will contain N lines corresponding to each of the N participants in the tournament and will contain the players name and their total score, separated by a hyphen.
Sample Input
2. Fraction Calculator
You are going to write a program to calculate the sum, difference, multiplication or division of two fractions and output the result in lowest terms.
The input file (FractionIN.txt) will start with the numerator and denominator of the first fraction on separate lines. The third line of the file will be either a + , – , *, / symbol to indicate the required operation. The last two lines of the file will be the numerator and denominator of the second fraction.
The output file (FractionOUT.txt) will contain the result of the indicated operation as a fraction in lowest terms all on one line.
Return To International Baccalaureate Computer Science Main Page