IB Computer Science Unit 1
IB Computer Science Unit 2
IB Computer Science Unit 3
IB Computer Science Unit 4
IB Computer Science Unit 5
IB Computer Science Unit 6

IB Computer Science Text File Input and Output using Java

IB Computer Science Learning Goals

In this IB Computer Science lesson you will be learning about:

  • Writing a program that reads information from a text file
  • Writing a program that writes and appends information to a text file

External File Basics

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

  • It can contain any kind of information: images, sound clips, binary numbers, or any other information
  • The format of the file is determined by the program that created that file.

Text files

  • Stores strings, characters, numbers, etc
  • Often has the extension .txt

Files can be accessed using 2 types of methods

Random Access

  • The program can start reading or writing at any place within the file
  • It can be opened for both input and output at the same time

Sequential Access

  • The program starts reading or writing at the start of the file only 
  • It cannot be opened for both reading and writing at the same time

In this course we will only look at sequential access of text files

 

Creating Text Files with Netbeans

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

IB-Computer-Science-FileIO (3)

Select Other and Choose Empty File

IB-Computer-Science-FileIO (1)

Name the file, choose the location.

IB-Computer-Science-FileIO (2)

File Input Streams

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 ( );

 

Examples of Reading Files

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

IB-Computer-Science-FileIO (4)

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.

IB-Computer-Science-FileIO (5)

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.

IB-Computer-Science-FileIO (6)

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.

IB-Computer-Science-FileIO (7)

Multiple Types of Data in 1 File

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.

IB-Computer-Science-FileIO (8)
IB-Computer-Science-FileIO (9)

File Output Streams

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

  • Write – Completely overwrites all data in the file before writing the new data
    • If you choose to write then any data currently in the file will be erased as soon as the first write occurs.
  • Append – Adds the new data to the end of a data file without overwriting the other data inside
    • Every time you run the program that writes to the data file, more data gets added to the end of the file.

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

  • You can use the println method to print to an output file with a new line character at the end
  • You can use the print method to print to an output file without a new line character at the end

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!!!!

File Output Examples

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

IB-Computer-Science-FileIO (10)

Files and Graphical User Interfaces

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

IB-Computer-Science-FileIO (11)

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

IB-Computer-Science-FileIO (12)

Find the number of values in the file

  • When opening the file stream or reading a value that code must be inside a try statement.
  • Our code loops until it reads an empty line from the file and as long as it reads a value it increments a counter.
  • We need to know how many numbers are in the file so we can create the array with the correct size
  • The file must be closed after so when we actually read the values into the array in the next step it will start back at the beginning of the file
IB-Computer-Science-FileIO (13)

Create the array and read the values in

  • Create the array using the counter from above
  • Try catch is needed since we are using a file
  • Now that we know the size of the file, we can use a counted loop to read each line and store into an array
  • Close the file as good practice
IB-Computer-Science-FileIO (14)

Calculating the values

  • No File access so don’t need try-catch statements
IB-Computer-Science-FileIO (15)

Write data to the file

  • Try – catch needed since using a file
  • Create the output file, no need to append to the end
  • Use regular output statements
  • Data won’t be written until the close command is executed
IB-Computer-Science-FileIO (16)

Practice Questions

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

IB-Computer-Science-FileIO (17)

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.