C# week November Black Friday
Black friday is here! Get up to 80 % extra points for free! More info
Only this week up to 80 % off on C# courses. More info

Lesson 3 - Working with text files in Java

In the previous lesson, Introduction to working with files in Java, we got acquainted with writing privileges in Windows operating systems. The simplest way to store application data on the hard drive is to use text files. I'm sure you all have already encountered files with the .txt extension. The text is simply stored there on multiple lines. Lines are separated by special characters, which are unfortunately OS-specific. Fortunately, Java solves this problem for us.

Note: On different projects online, you may encounter using different classes and approaches for writing into files. I'll show you the simplest and latest approaches.

Writing text to a new file

First, let's create a new text file and write something into it. Create a new project (a console application) and name it TextFiles. Java provides the BufferedWriter class for us which is used to write into text files. A buffer is temporary memory to speed up writing to the disk.

Next, we'll create a try-with-resources block and create a new BufferedWriter instance inside. As we already know from previous lessons, try-with-resources will automatically close the file once the reading/writing is finished. We'll pass a FileWriter instance which wraps the BufferedWriter through the constructor:

try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt")))
{
}
catch (Exception e)
{
    System.err.println("Unable to write the file.");
}

It's worth mentioning the use of System.err in the catch block, which is an error output channel. If the writing doesn't work, you'll see this text in red in the console.

Our BufferedWriter now points to the appropriate file. We write a new line in text files using the write() method. We can break the line by the newLine() method. Once we're done writing, we'll have to call the flush() method, which takes care of emptying the buffer. We won't have to deal with any of that, all we have to remember is that any written lines may remain in the buffer memory for a while, so we force to write them using the flush() method.

At this point, the code looks something like this:

try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt")))
{
    bw.write("The first line");
    bw.newLine();
    bw.write("This text is on the second line");
    bw.newLine();
    bw.write("And the third one.");
    bw.newLine();
    bw.flush();
}
catch (Exception e)
{
    System.err.println("Unable to write the file.");
}

Once we run it, a file named file.txt will be created in our project folder. We have already gone over how to handle file path and writing privileges in Java correctly, so we won't deal with any of that here so as to keep the code simple. As you can see, the file now exists and contains the text we designated:

Writing to text files in Java

Appending text to an existing file

If the file doesn't exist, the code above will create it. If it does exist, it will be overwritten. This behavior can be altered by specifying the second parameter in the FileWriter's constructor. If we set it to true, it'll append text rather than overwrite it. We add a new line to an existing file like this:

try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt", true)))
{
    bw.write("The appended line");
    bw.newLine();
    bw.flush();
}
catch (Exception e)
{
    System.err.println("Unable to write the file.");
}

If the file doesn't exist, it'll be created. If it exists, it'll be appended and its original content will remain.

Reading an existing file

The only thing left for us to learn is how to read a file. It isn't any more complicated than writing. As usual, there is a Java class for it - BufferedReader. It works pretty much like BufferedWriter, but instead of the write() method we use readLine() which returns a line of text from the file and moves to the next line. With this in mind, we'll call it in a while loop. The condition to avoid reading beyond the file may seem a little tricky, however, all we're doing is checking whether the line has been assigned to the variable.

The code to print the file contents to the console would look like this:

try (BufferedReader br = new BufferedReader(new FileReader("file.txt")))
{
    String s;
    while ((s = br.readLine()) != null)
    {
        System.out.println(s);
    }
}
catch (Exception e)
{
    System.err.println("Unable to read the file.");
}

The code for our entire application now looks similar to this:

// writing to the file
try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt")))
{
    bw.write("The first line");
    bw.newLine();
    bw.write("This text is on the second line");
    bw.newLine();
    bw.write("And the third one.");
    bw.newLine();
    bw.flush();
    System.out.println("The file has been successfully written.");
}
catch (Exception e)
{
    System.err.println("Unable to write the file.");
}

// appending a text to the file
try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt", true)))
{
    bw.write("An appended line");
    bw.newLine();
    bw.flush();
    System.out.println("A new line has been successfully appended into the file.");
}
catch (Exception e)
{
    System.err.println("Unable to write the file.");
}

// printing the contents of the file
System.out.println("Printing file contents:");
try (BufferedReader br = new BufferedReader(new FileReader("file.txt")))
{
    String s;
    while ((s = br.readLine()) != null)
    {
        System.out.println(s);
    }
}
catch (Exception e)
{
    System.err.println("Unable to read the file.");
}

The result:

Console application
The file has been successfully written.
A new line has been successfully appended into the file.
Printing file contents:
The first line
This text is on the second line
And the third one.
An appended line

In this article, we've omitted writing privileges. Next time, in the lesson Storing objects in the CSV format in Java, we'll look into storing objects into files.


 

Download

Downloaded 0x (21.13 kB)
Application includes source codes in language Java

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Previous article
Introduction to working with files in Java
All articles in this section
Files and I/O in Java
Thumbnail
Next article
Storing objects in the CSV format in Java
Activities (3)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!