Using files in programming

Files in programming is a very important topic. It is usually taught in introductory programming courses because of its importance.

In this post, you will learn why we need files in programming and some examples of how to use them.

Table of Contents

What is a file in programming?

As stated in Wikipedia: “A computer file is a computer resource for recording data in a computer storage device. Just as words can be written to paper, so can data be written to a computer file. Files can be edited and transferred through the Internet on that particular computer system.”

So, when we refer to files or just file in programming, we mean to be able to handle computer files (see the definition above) from your code. All programming languages offer tools to handle files and most of them work similarly.

By handling computer files, we mean:

  • create files,
  • read data from a file and,
  • write data to a file

Why do we need files in programming?

A computer can store data in two ways:

An example of the use of RAM to store data is in programming when you create an integer variable and assign a number to it. In this case, the value you assigned to the variable is stored in RAM. This way of store data is very efficient. However, if you restart the computer, the data will be lost.

So, how do we store data more permanently?

Your guess is right, using computer files.

Once you store data on a computer file, the data will be there if you restart your computer. The only way to lose that data is if you delete the file, or the hard drive fails.

In some books, the authors refer to store data in a file as to persist the data or make the data persistent. It means that even you shut down the computer, the data is still there and you will be able to have access to the data once you switch on your computer again.

Applications of files in programming

Files are all over in programming and computers.

I’ll list below some of the applications of files (it will probably take several books to mention all of them, if possible):

  • databases: ” A database is an organized collection of structured information, or data, typically stored electronically in a computer system. ” Source Oracle website. From the previous definitions, you can see that the data is stored in computer files. You just have a higher-level abstraction (and language) to have access to that data through a Database Management System.
  • Word processors. Apple Pages, Microsoft Words are two examples of word processors. They use computer files to store data, the document you wrote, so later you can have access to what you wrote.
  • Operating Systems (OS). Every OS makes extensive use of computer files.
  • Programming (of course). The first use in programming is that the code you write, is stored in a computer file, so next time you work on it you don’t have to start from scratch again. The second use is to store data generated by the software you create. Let’s say you create an accounting software. The transactions and accounts have to be persisted in a computer file.

Example of using files in Java

It is important that before you start including files in your code, you learn exceptions. In this post, you can get the big picture of exceptions and some examples, including one using files.

Before start working with files, you must remember these steps:

  • First, open a file or create it if it does not exist
  • Write data to the file or read data from it
  • Close the file

It is of utmost importance that you close the file(s) always. If you leave the file open, it can create inconsistencies making the file corrupted. In this case, you will lose all the data stored in that file.

Java classes to work with files in programming

There are many classes that you can use to work with files in Java. Here I’m just going to show you three of them. These are enough for the examples I’ll show you next.

  • File: “An abstract representation of file and directory pathnames”. Source.
  • PrintWriter: “Prints formatted representations of objects to a text-output stream”. Source.
  • Scanner: ” A simple text scanner which can parse primitive types and strings using regular expressions”. Source. This class is mainly used to read data from the keyboard, but it can also be used to read data from a text file.

Example 1: Saving data to a file

A lecturer wants to save the data of a student group to a file. From each student, the lecturer knows the name, student number and marks on certain modules.

Create the classes that model this situation and create a method that saves the data of all students to a file named “students.txt”.

To solve this, we need first to design the classes, then implement the method. From the description above, we can identify three classes named: GroupOfStudents, Student, Mark.

Find the implementation below.

public class Mark {

    private String module;
    private int mark;

    public Mark(String module, int mark) {
        this.module = module;
        this.mark = mark;
    }

    @Override
    public String toString(){
        return module + "-" + mark;
    }
}

class Student{

    String name;
    String studentNumber;
    List<Mark> marks;

    public Student(String name, String studentNumber){
        this.name = name;
        this.studentNumber = studentNumber;
        marks = new ArrayList<>();
    }

    public Student(String name, String studentNumber,  List<Mark> marks) {
        this.name = name;
        this.studentNumber = studentNumber;
        this.marks = marks;
    }

    @Override
    public String toString(){
        String marks = "";
        for (Mark mark: this.marks){
            marks = marks + mark.toString() + ",";
        }
        return name + ", " + studentNumber + ", " + marks;
    }
}

class GroupOfStudents{
    Student []  students;
    int amount;

    public GroupOfStudents(){
        students  = new Student[100];
        amount = 0;
    }

    public void addStudent(Student student) throws Exception {
        if (amount<99){
            students[amount++] = student;
        }
        else
            throw new Exception("No more students are allowed");
    }

    public void Save(String filename) throws FileNotFoundException {
        File f;
        PrintWriter pw = null;
        try {
            f = new File(filename);
            pw = new PrintWriter(f);
            for (int i = 0; i < amount; i++) {
                pw.println(this.students[i].toString());
            }
        } finally {//Always close the file.
            pw.close();
        }
    }
}

Notice the method Save of the class GroupOfStudents. We used two of the three classes mentioned in the previous section: File and PrintWriter.

Also notice that we closed the file within the finally block. This will ensure that the file is always closed.

Example 2: Console application to save to a file and read from the previously created file

Using the same situation of Example 1 above, we now are going to create a console application that will save the data of students to a file and will read from that file and print on the screen.

class ConsoleApp {

    public static void main(String[] args) {

        List<Mark> student1Marks = new ArrayList<>();
        student1Marks.add(new Mark("OOPI", 50));
        student1Marks.add(new Mark("OOPII", 60));
        student1Marks.add(new Mark("Math4CS", 50));

        List<Mark> student2Marks = new ArrayList<>();
        student2Marks.add(new Mark("OOPI", 80));
        student2Marks.add(new Mark("OOPII", 80));
        student2Marks.add(new Mark("Math4CS", 80));

        List<Mark> student3Marks = new ArrayList<>();
        student3Marks.add(new Mark("OOPI", 50));
        student3Marks.add(new Mark("OOPII", 50));
        student3Marks.add(new Mark("Math4CS", 50));


        Student student1 = new Student("Jhon", "2017120084",  student1Marks);
        Student student2 = new Student("Maria", "2017121084",  student2Marks);
        Student student3 = new Student("Smith", "2017124084", student3Marks);



        GroupOfStudents students = new GroupOfStudents();

        try {
            students.addStudent(student1);
            students.addStudent(student2);
            students.addStudent(student3);
        } catch (Exception e) {
           System.out.println("The students could not be added.");
        }


        try {
            students.Save("students.txt");
        }
        catch (Exception e){
            System.out.println("The information could not be saved to a file.");
        }


        System.out.println("Reading from the file ...");
        try {
            Scanner scanner = new Scanner(new File("students.txt"));
            while (scanner.hasNext()){
                System.out.println(scanner.nextLine());
            }
        }
        catch (FileNotFoundException e){
            System.out.println("The file does not exist.");
        }
    }
}

Extra practice

To practice more your new knowledge, I recommend you modify the example 1 and 2 implementation as follows:

  • Save the data of the students to a file (This is already implemented in example 2).
  • Create a new object of the type GroupOfStudents within the console application.
  • Use the data that you read from the file to create new student objects and add them to the group of student object you created before.
  • Print in the screen all the information of the students using the newly created group of students object and compare the result with what was printed when reading from the file.

If you need extra guidance to do the previous, leave a comment below and will help you to finish your own example.

Summary

Files is an important topic in programming. If you want to be a good programmer, you definitely need to master this topic.

In this post, I only address plain text files. There is another type of file that you can work with once you master text files.

Make sure you always close an open file, otherwise it can create a corrupt file and you will lose the data you store in it.

H@ppy coding!