Computer Language
Lecture 11-1

Files and reading data

Josue Obregon

Seoul National University of Science and Technology
Information Technology Management
Lecture slides index

May 19, 2025

Class contents

  1. Introduction to Computer Programming and Java
  2. Reading Input and Strings
  3. Variables and calculation with numbers
  4. Conditional statements
  5. Repeating functionality
  6. Methods
  7. Lists, Arrays and Strings
  8. Midterm
  1. Introduction to Object Oriented Programming
  2. More of Object Oriented Programming
  3. Inheritance and Interfaces I
  4. Inheritance and Interfaces II
  5. Class diagrams, packages and exceptions
  6. Project Live Code Review and Evaluation
  7. Final examination

Agenda

  • Files and filesystem
  • Reading files with Scanner
  • try-catch and exceptions
  • CSV parsing and objects
  • File-based exercises

Learning Objectives

  • You know what a file and a filesystem are, and are able to add an empty text file into the filesystem.
  • You know how to create a write a program that reads data from a file.
  • You can add objects to a list
  • You can go through objects in a list

Introduction

  • A considerable amount of software is in one way or another based on handling data.
  • Software created for playing music handles music files and those created for the purpose of image manipulation handle image files.
  • Applications that run on the internet and mobile devices, such as Facebook, WhatsApp, and Telegram, handle user information that is stored in file-based databases.
  • What these all have in common is that they read and manipulate data in one way or another.
  • Also, the data being handled is ultimately stored in some format in one or more files.

Reading From the Keyboard

  • We’ve been using the Scanner-class since the beginning of this course to read user input.
  • The block in which data is read has been a while-true loop where the reading ends at a specific input.
Scanner scanner = new Scanner(System.in);

while (true) {
    String line = scanner.nextLine();

    if (line.equals("end")) {
        break;
    }

    // add the read line to a list for later
    // handling or handle the line immediately

}
  • In the example above, we pass system input (System.in) as a parameter to the constructor of the Scanner-class.
  • In text-based user interfaces, the input of the user is directed into the input stream one line at a time, which means that the information is sent to be handled every time the user enters a new line.
  • The user input is read in string form.
  • If we wanted to handle the input as integers, for instance, we’d have to convert it to another form.

Files and the Filesystem

  • Files are collections of data that live in computers.
  • These files can contain, among other things, text, images, music, or any combination of these.
  • The file format determines the content of the file as well as the program required to read the file.
  • For example, PDF files are read with a program suited for reading PDF files, and music files are read with a program suited for reading music files.
  • Each of these programs is made by humans, and the creators of these programs – i.e., programmers – also specify the file format as part of the work.

Files and the Filesystem

  • Computers have several different programs for browsing files.
  • These programs are specific to the operating system.
  • All programs used for browsing files make use of the filesystem of the computer in one way or another.
  • Our development environment provides us with the ability to browse the files of a project.
  • In NetBeans you can take a look at all the files attached to a project by selecting the Files tab, which is found in the same place as the Projects tab.
  • If the tab cannot be be found, it can be opened from the Window menu.
  • Clicking the project to open it will reveal all its files.

Exercise 1 - Creating a New File

  • In this exercise, we won’t be programming.
  • Instead, you’ll familiarize yourself with the Files-tab in NetBeans and how to create a new file.
  • Create a file called file.txt in the root folder (the folder containing the folder src and the file build.xml) of the exercise template using the Files-tab in NetBeans.
  • Edit the file and write the message Hello, world! on the first line of the file.

The Concrete File Storage Format

  • Files exist on the hard drive of a computer, which is, in reality, a large set of ones and zeros, i.e., bits.
  • Information is made up of these bits, e.g., one variable of type int takes up 32 bits (i.e., 32 ones or zeros).
  • Modern terabyte-sized hard drives hold about 8 trillion bits (written out the number is 8,000,000,000,000).
  • On this scale, a single integer is very small.
  • Files can exist practically anywhere on a hard drive, even separated into multiple pieces.
  • The computer’s filesystem has the responsibility of keeping track of the locations of files on the hard drive as well as providing the ability to create new files and modify them.
  • The filesystem’s main responsibility is abstracting the true structure of the hard drive; a user or a program using a file doesn’t need to care about how, or where, the file is actually stored.

Reading From a File

  • Reading a file is done using the Scanner-class.
  • When we want to read a file using the Scanner-class, we give the path for the file we want to read as a parameter to the constructor of the class.
  • The path to the file can be acquired using Java’s Paths.get command, which is given the file’s name in string format as a parameter: Paths.get("filename.extension").
  • When the Scanner-object that reads the file has been created, the file can be read using a while-loop.
  • The reading proceeds until all the lines of the file have been read, i.e., until the scanner finds no more lines to read.
  • Reading a file may result in an error, and it’s for this reason that the process requires separate blocks - one for the try, and another to catch potential errors.

Reading From a File example

// first
import java.util.Scanner;
import java.nio.file.Paths;

// in the program:

// we create a scanner for reading the file
try (Scanner scanner = new Scanner(Paths.get("file.txt"))) {

    // we read the file until all lines have been read
    while (scanner.hasNextLine()) {
        // we read one line
        String row = scanner.nextLine();
        // we print the line that we read
        System.out.println(row);
    }
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}
  • A file is read from the project root by default ( when new Scanner(Paths.get("file.txt")) is called), i.e., the folder that contains the folder src and the file build.xml (and possibly other files as well).
  • The contents of this folder can the inspected using the Files-tab in NetBeans.

Handling exceptions

  • We use the try {} catch (Exception e) {} block structure to handle exceptions.
  • The keyword try starts a block containing the code which might throw an exception.
  • The block starting with the keyword catch defines what happens if an exception is thrown in the try block.
  • The keyword catch is followed by the type of the exception handled by that block, for example “all exceptions” catch (Exception e).
try {
    // code which possibly throws an exception
} catch (Exception e) {
    // code block executed if an exception is thrown
}
  • We use the keyword catch, because causing an exception is referred to as throwing an exception.

Exceptions and resources

  • There is separate exception handling for reading operating system resources such as files.
  • With so called try-with-resources exception handling, the resource to be opened is added to a non-compulsory part of the try block declaration in brackets.
  • The code that we saw before reads all lines from “file.txt” and adds print them out in the screen.
  • Reading a file might throw an exception, so it requires a try-catch block.
  • The try-with-resources approach is useful for handling resources, because the program closes the used resources automatically.
  • Now references to files can “disappear”, because we do not need them anymore.
  • If the resources are not closed, the operating system sees them as being in use until the program is closed.

Exercise 2 - Printing a File

  • Write a program that prints the contents of a file called “data.txt”, such that each line of the file is printed on its own line.

  • If the file content looks like so:

In a
world
  • Then the program should print the following:
In a
world

Exercise 3 - Printing a Specified File

  • Write a program that asks the user for a string, and then prints the contents of a file with a name matching the string provided.
  • You may assume that the user provides a file name that the program can find.
  • You may use the files “data.txt” and “song.txt”, when testing the functionality of your program.
  • The output of the program can be seen below for when a user has entered the string “song.txt”.
  • The content that is printed comes from the file “song.txt”.
  • Naturally, the program should also work with other filenames, assuming the file can be found.
Which file should have its contents printed?
(user input) song.txt
I code in the morning, with coffee by my side,
Semicolons dancing, in a class I can't hide.
Compile my dreams, run my soul, Java keeps me whole!
Bugs come at midnight, but I fix them with pride.
From SeoulTech to sunrise, let the logic be my guide.

Another example

  • In the example below, we read all the lines of the file “file.txt”, which are then added to an ArrayList.
ArrayList<String> lines = new ArrayList<>();

// we create a scanner for reading the file
try (Scanner scanner = new Scanner(Paths.get("file.txt"))) {

    // we read all the lines of the file
    while (scanner.hasNextLine()) {
        lines.add(scanner.nextLine());
    }
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}

// we print the total number of lines
System.out.println("Total lines: " + lines.size());

Exercise 4 - Guest List From a File

  • Write a program that asks the user for a string, and then loads the contents of a file with a name matching the string provided.
  • The content of the file is a list of names, one line per name.
  • Load the names into an ArrayList.
  • After that, the program asks the user for a name, and it checks whether names entered by the user are on the guest list.
  • You can use the files “guestList.txt” and “guestList2.txt” for testing your program.
Name of the file:
(user input) guestList.txt

Enter names, an empty line quits.
(user input) Chuck Norris
The name is not on the list.
(user input) Jack Baluer
The name is not on the list.
(user input) Kim Yuna
The name is on the list.
(user input) Elon Musk
The name is on the list.
(user input) IU
The name is on the list.

Thank you!

Exercise 5 - Is it in the file?

  • Write a program that first asks the user for the name of the file to be read, after which the user is prompted for the string that they’re looking for.
  • The program then reads the file and searches for the desired string.
  • If the string is found, the program should print “Found!”.
  • If not, the program should print “Not found.”.
  • If reading the file fails (the reading ends in an error) the program should print the message “Reading the file” + file + ” failed.”.
  • You can use the files “guestList.txt” and “guestList2.txt” for testing your program.
  • You can create your own files for testing.
Name of the file:
(user input) guestList.txt
Search for:
(user input) Lionel
Not found.
Name of the file:
(user input) guestList2.txt
Search for:
(user input) Jennie
Found!
Name of the file:
(user input) nonexistent.txt
Search for:
(user input) test
Reading the file nonexistent.txt failed.

An Empty Line In a File

  • Sometimes an empty line finds it way into a file.
  • Skipping an empty line can be done using the command continue and the isEmpty-method of the string.
  • In the example below, we read from a file
  • Reading data is straightforward.
// we create a scanner for reading the file
try (Scanner scanner = new Scanner(Paths.get("file.csv"))) {

    // we read all the lines of the file
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        // if the line is blank we do nothing
        if (line.isEmpty()) {
            continue;
        }

        // do something with the data

    }
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}

Reading Data of a Specific Format From a File

  • The world is full of data that are related to other data - these form collections.
  • For example, personal information can include a name, date of birth and a phone number.
  • Address information, on the other hand, can include a country, city, street address, postal number and so on.
  • Data is often stored in files using a specific format.
  • One such format that’s already familiar to us is comma-separated values (CSV) format, i.e., data separated by commas.
  • A program that reads data from a csv file called records.csv would look like this :
try (Scanner scanner = new Scanner(Paths.get("records.csv"))) {

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        String[] parts = line.split(",");
        String name = parts[0];
        int age = Integer.valueOf(parts[1]);

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

Exercise - Records From a File

  • In this exercise, we’ll be working with files stored in CSV-format that contain names and ages separated by commas.
  • The file format may look like this:
lily,3
anton,5
levi,4
amy,1
  • Your task is to write a program that first prompts the user for the name of the file they want to read.
  • The program then prints the content of the file in the following way (we’re assuming below that the output is from the above-mentioned file):
Name of the file:
(user input) data.txt
lily, age: 3 years
anton, age: 5 years
levi, age: 4 years
amy, age: 1 year
  • Note: The word “year” should be formatted based on the age.

Adding object to a list

  • Strings are objects, so it should come as no surprise that other kinds of objects can also be found in lists.
  • Next, let’s examine the cooperation of lists and objects in more detail.
  • Let’s assume we have access to the class Person defined in our previous lecture, describing a person (see the next tab).
  • Handling objects in a list is not really different in any way from the previous experience we have with lists.
  • The essential difference is only to define the type for the stored elements when you create the list.
  • In the example below we first create a list meant for storing Person type object, after which we add persons to it.
  • Finally the Person objects are printed one by one.
ArrayList<Person> persons = new ArrayList<>();

// a person object can be created first
Person john = new Person("John");
// and then added to the list
persons.add(john);

// person objects can also be created "in the same sentence"
// that they are added to the list
persons.add(new Person("Matthew"));
persons.add(new Person("Martin"));

for (Person person: persons) {
    System.out.println(person);
}
John, age 0 years
Matthew, age 0 years
Martin, age 0 years
public class Person {

    private String name;
    private int age;
    private int weight;
    private int height;

    public Person(String name) {
        this.name = name;
        this.age = 0;
        this.weight = 0;
        this.height = 0;
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }

    public void growOlder() {
        this.age = this.age + 1;
    }

    public void setHeight(int newHeight) {
        this.height = newHeight;
    }

    public void setWeight(int newWeight) {
        this.weight = newWeight;
    }

    public double bodyMassIndex() {
        double heightDivByHundred = this.height / 100.0;
        return this.weight / (heightDivByHundred * heightDivByHundred);
    }

    @Override
    public String toString() {
        return this.name + ", age " + this.age + " years";
    }
}

Reading Objects From a File

  • Creating objects from data that is read from a file is straightforward.
  • Let’s assume that we have a class called Person, as well as the data from before.
  • Reading objects can be done like so:
ArrayList<Person> people = new ArrayList<>();

try (Scanner scanner = new Scanner(Paths.get("records.txt"))) {

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        String[] parts = line.split(",");
        String name = parts[0];
        int age = Integer.valueOf(parts[1]);

        people.add(new Person(name, age));
    }
}

System.out.println("Total amount of people read: " + people.size());
  • Reading objects from a file is a clear responsibility in and of itself, and should for that reason be isolated into a method.
  • This is what we’ll be doing in the next exercise.

Exercise 6 - Storing Records

  • In this exercise, we’ll be working with files stored in CSV format, which contain names and ages separated by commas.
  • The file format may look like this:
lily,3
anton,5
levi,4
amy,1
  • The exercise template already has a Person class, and the class StoringRecords has a body for the method public static ArrayList<Person> readRecordsFromFile(String file).
  • Implement the readRecordsFromFile method such that it reads the persons from the file passed as a parameter, and finally returns them in the list returned by the method.
  • The exercise template has a main method that you can use to test how your program works.
public class Person {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return this.name + ", age: " + this.age;
    }

}
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;

public class StoringRecords {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Filename:");
        String file = scan.nextLine();

        ArrayList<Person> records = readRecordsFromFile(file);
        System.out.println("Persons: " + records.size());
        System.out.println("Persons:");
        for (Person person : records) {
            System.out.println(person);

        }
    }

    public static ArrayList<Person> readRecordsFromFile(String file) {
        ArrayList<Person> persons = new ArrayList<>();

        // Write here the code for reading from file
        // and printing the read records
        return persons;

    }
}

Filtered printing from the list

  • You can also examine the objects on the list as you go through it.
  • In the example below, we first ask the user for an age restriction, after which we print all the objects whose age is at least the number given by the user.
// Assume we have a 'persons' list
// that consists of person objects

System.out.print("What is the age limit? ");
int ageLimit = Integer.valueOf(scanner.nextLine());

for (Person person: persons) {
    if (person.getAge() >= ageLimit) {
        System.out.println(person);
    }
}

Exercise 7 - Sport Statistics

  • In this exercise, we’ll be working with files stored in CSV format.
  • Each line of the file contains the home team, visiting team, home team points, and visiting team points, all separated by commas.
    • Create a proper Team class that is able to store the name of the team, number of games, number of wins and number of losses.
      • Add the proper behavior to the Team class that implements the setters and getters needed for this exercise.
  • You can see an example of the file’s contents in the next tab.
  • You can also get the contents of file games.csv in the previous link.
  • Write a program that prompts the user for a filename, after which it reads the match statistics from the file
    • It creates an ArrayList<Team> and extract the team information from each match record on the file.
  • The program then prompts the user for the name of a team, and prints the team name, number of games, number of wins and losses of the given team.
  • The winner of a game is the team that has gained more points from it.
  • You may assume that the games cannot be tied.
  • You can refer to the sample outputs.
  • You can see an example below of the file’s contents.
Doosan Bears,LG Twins,9,16
Doosan Bears,LG Twins,16,12
Doosan Bears,LG Twins,9,16
Doosan Bears,KIA Tigers,10,16
Hanwha Eagles,Doosan Bears,0,16
Hanwha Eagles,Doosan Bears,3,16
Lotte Giants,NC Dinos,7,16
Lotte Giants,SSG Landers,16,1
File:
(user input) games.csv
Team:
(user input) Doosan Bears
Games: 6
Wins: 3
Losses: 3

File:
(user input) games.csv
Team:
(user input) Lotte Giants
Games: 2
Wins: 1
Losses: 1

Checking our learning objectives

  • You know what a file and a filesystem are, and are able to add an empty text file into the filesystem.
  • You know how to create a write a program that reads data from a file.
  • You can add objects to a list
  • You can go through objects in a list

Acknowledgements


Back to title slide Back to lecture slides index