Saving and reading data from files is more advanced topic in Java, but when it comes to text files things are not as difficult as you might think. To communicate efficiently with existing data on our disk, first of all we need to learn a few basic classes.

The basic class that will allow us to create an object storing data file is File. We create them in the following way:

In this way, we have a File object called a file that will allow us to operate on it.

Reading:

The previously learned Scanner class allows the simplest data reading. To create a stream, use this structure:

We see here a typical for Java and object-oriented languages, a construction that consists of passing one object as an argument to create another. The Scanner class “encapsulates” the File class, extending its functionality to the ability to read the file. Later we will see that there can be many more such nesting.

When we have a Scanner object created with the appropriate File object passed to it, we can already use the appropriate methods, i.e. like in the console the following instruction will be correct:

In this way, we load the text line from the text file into the text variable. Let’s check it out with an example. Create a file in which you can write one arbitrary line of text, for example “My first text in file”. Save it as myText.txt. The program code to read this sentence would look like:

Remember to keep the file in the same folder as the .class file, otherwise specify the path to the file in place of its name.

You might notice here one strange thing, namely the entry FileNotFoundException – this is an exception that we must add, without it our code will not work.

Write:

Another important thing is writing to a file. We can use the PrintWriter class here, and create its object, but note as the constructor parameter here is the file name, not the File object.

We will write to the myText.txt file the sentence “New line of text” using the print () method.

It is very important to close all output streams, we do it using the close () method, once we no longer write anything with the help of the object. After opening the myText.txt file, we will see the our new sentance.

LEAVE A REPLY

Please enter your comment!
Please enter your name here