Learn Java Easy. Chapter 14. Reading and Writing Text Files

Chapter 14. Reading and Writing Text Files

Now that we have the record of medicines stolen by Phil, it’s time to blackmail him. Pedro will meet with him today. We have no doubt that he will cooperate. If we presented the evidence, he would not only be fired, but he would also be involved in a legal process where he would possibly be sentenced to some years in prison.

 

The plan is working perfectly. No one suspects anything, and we’ve already overcome more than half the way. Before the final step, and finally getting out, we still need two things: to have a record of the security measures that await us in the last stretch before the exit and to access the guards’ communication.

 

 

I haven’t told you yet because it’s crazy, but the idea is to leave through the main door. It seems like suicide, but no one will suspect that someone would try to escape through there. As you can imagine, it’s the most guarded part of the prison and we need to know exactly what we’re up against.

 

To analyze the guards’ activity and tasks, we have some records of the guards’ activities. These are in text format and we need to create Java Programs to help us understand the information they contain and even modify it if necessary.

 

As usual, I have no idea what’s happening outside. I hope Chani is taking care of everything and that she’s in communication with Rich. I hope that when I get out, I don’t find out that Rich has fled and that all this effort has been in vain.

 


On the other hand, I’m still in contact with my family, but I’ve lost some contact with my close friends. The truth is that right now I don’t want to have visits. I’m focused on the escape plan. I don’t want to think about what people might be saying about me. That could affect me. I’m going to prove my innocence and show everyone who doubts me that they’re wrong.

 

 

 

 

It seems that my private tutor is ready to teach me how to read and edit files using Java. The truth is that it’s not a topic that particularly excites me, but it’s necessary to continue with this plan. Bud has already warned me that it’s possibly the most complex part of the entire curriculum, so I need to prepare myself mentally. Although with such a good teacher, I’m sure it won’t be difficult to understand it.

Importance of Reading and Writing Files in Java

 

As you’re taking your first steps in Java, reading and writing files in Java is probably not a priority for you. Most Programs don’t need this functionality. However, it wouldn’t be smart to ignore that it’s a fundamental tool for many applications. When reading a file, an application can process external data and work with it. Just as we’ve been giving instructions manually to our Programs so far, now they can follow these same guidelines from a text file.

 

Similarly, writing to files allows Programs to save results, create logs, or store important data that can later be used or analyzed.

 

Another important advantage is that Java offers a wide variety of classes and methods within its library to handle files safely and easily. This facilitates the manipulation of large volumes of data, whether in text or binary format. Additionally, file handling in Java is essential for developing applications that require data persistence, such as information management systems or databases.

Reading Text Files

 

In my opinion, when learning Java, the important thing is not to memorize concepts like a parrot, but to understand how Programming works and comprehend the logic behind it. If you do it this way, it will be much easier for you; the feeling of progress will be much more satisfying and, moreover, you’ll know how to Program for the rest of your life. It’s true that if you spend a long time without touching code, you might not remember almost anything, but by dedicating a few hours, that knowledge quickly returns to your head.

 

After so many hours Programming, you’ll already have quite advanced knowledge of Java syntax. What seemed impossible to learn at the beginning now makes sense and even seems simple. Not everyone gets this far, so congratulations.

 

For this specific topic, and much to my regret, we’ll have to learn some things by memory. For our Programs to read and write text, we have to import a series of classes.

Importing the Necessary Classes for Reading Files

 

import java.io.File;

import java.io.FileReader;

import java.io.BufferedReader;

import java.io.IOException;

 

 

Creating a File Object that Represents the Text File

 

Obviously, if you have a file that you want to work with, you don’t need to create it, but you do need to know the path where the file is located on your computer.

 

File file = new File(“path/to/file.txt”);

 

This is an example of a real file path that I use for example exercises:

 

File file = new File(“C:\Users\ribeh\IdeaProjects\Project 1\activity.txt”);

 

 

Reading the File Using FileReader and BufferedReader

 

I’d like to tell you that the Program can already read the data from our file and even print it on the screen, but that’s not the case. There’s still one more step.

 

We need to use try and catch, but since we already know how they work, there won’t be any problem.

 

try (FileReader fr = new FileReader("activity.");
    BufferedReader br = new BufferedReader(fr)) {

        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line); // Prints each line of the file
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

 

We call the FileReader “fr” and the BufferedReader “br”, but you can use whatever name suits you best. Then we create a while loop that goes through the lines of our file and keeps printing as long as there is data to print. The last part is the catch block in case there’s any exception.

 

 

Writing Text Files

 

Again, we’ll need to import the necessary classes. In this case, they are these:

 

import java.io.File;

import java.io.FileWriter;

import java.io.BufferedWriter;

import java.io.IOException;

 

Of course, we’ll need to have the path to our file. I’ve already explained how the path should be:

 

File file = new File(“path/to/file.txt”);

 

This is an example of a real file path that I use for example exercises:

 

File file = new File(“C:\Users\ribeh\IdeaProjects\Project 1\activity.txt”);

 

Writing to the File Using FileWriter and BufferedWriter

 

 

Write to the file using FileWriter and BufferedWriter

 

String activity = "activity.txt"; // Define the file name
try (FileWriter fw = new FileWriter(activity);
     BufferedWriter bw = new BufferedWriter(fw)) {

    bw.write("Hello, this is a new text file.");
    bw.newLine(); // Adds a new line
    bw.write("Here we can add more content.");

} catch (IOException e) {
    e.printStackTrace();
}

 

We’ve used “Fw” to refer to our FileWriter and “Bw” for the BufferedWriter, but, as in the previous case, we could give them another name if it suits us better. In this case, we don’t need to create a loop inside the try block because we don’t need to go through all the lines. We only need to add one or several lines. Finally, logically, we close with the catch block in case a possible exception occurs.

Summary of What We’ve Learned

 

To read text files in Java, the first thing we need to do is import the File, FileReader, BufferedReader, and IOException classes. To read a file, you must choose that document and copy its path. Then, you use FileReader and BufferedReader to read the file line by line and display its contents. It’s essential to handle possible exceptions with try and catch blocks so the Program can manage any errors that arise. Fortunately, we learned how to do this in the previous topic.

 

Let’s look at the other side of the coin: writing to those text files. To start, you also need to import some classes, which in this case are: File, FileWriter, BufferedWriter, and IOException. Just like before, we’ll need the path to our file. Then, we’ll use FileWriter and BufferedWriter to write content to the file, adding new lines when necessary. It’s crucial to handle exceptions in this process to ensure that any problems during writing are handled appropriately.

 

These steps allow you to effectively read and write text files in Java, managing errors and exceptions in a controlled manner.

Did you like it? Don’t keep it to yourself β€” share it like juicy gossip! 😏