Java Read File With Hard Return on Line

Manipulating text files is a skill that will serve you well in your programming career. In this section, you lot'll learn how to open and how to write to a text file. Simply by text file, we but mean a file with text in it - simple as that! You lot can create a text file in programmes like Notepad on a Windows calculator, TextEdit on a Mac, Gedit in a Linux/Gnome environment.

The first thing we'll do is to open upward a text file and read its contents.

Reading a Text File

Start a new projection for this. Telephone call the package textfiles and the class FileData. Add an import statement just beneath the package line and before the class proper name:

import java.io.IOException;

Your coding window volition then await like this:

Blank main method in Java

To deal with annihilation going wrong with our file handling, add the post-obit to the main method (the text in bold):

public static void main(Cord[ ] args) throws IOException {

}

We're telling Java that the main method will throw up an IOException mistake, and that it has to exist dealt with. Later, we'll add a try … catch block to brandish an appropriate fault bulletin for the user, should something go wrong.

To open up the text file, let's create a new class. And so click File > New File from the NetBeans carte at the tiptop. Create a new Java Class file and give it the name ReadFile. When your new form is created, add the following three import statements:

import java.io.IOException;
import java.io.FileReader;
import coffee.io.BufferedReader;

Your new class should then look like this 1:

Your ReadFile Java class

(The import lines are underlined because we haven't done anything with them yet. This is a NetBeans feature.)

We'll create a new object from this class to read a file. Add together the following constructor to your code, along with the private String field called path:

The class constructor

All we're doing here is passing in the name of a file, and and then handing the file name over to the path field.

What we now need to do is create a method that returns all the lines of code from the text file. The lines will be held in an assortment. Add together the following method proclamation that will open up the file:

A method to open a file

Don't worry about the scarlet underline: it will become away once we've added some lawmaking. NetBeans has just added it because we have no return statement.

Notice that the method is gear up to return a Cord array, though:

public String[ ]

The array volition contain all the lines from the text file.

Notice, likewise, that we've added "throws IOException" to the end of the method header. Every method that deals with reading text files needs one of these. Coffee volition throw any errors up the line, and they volition exist caught in our main method.

To read characters from a text file, the FileReader is used. This reads bytes from a text file, and each byte is a unmarried character. Y'all can read whole lines of text, rather than single characters. To do this, you lot tin can hand your FileReader over to something chosen a BufferedReader. The BufferedReader has a handy method chosen ReadLine. As its proper noun suggests, it is used to read whole lines, rather than unmarried characters. What the BufferedReader does, though, is to store characters in memory (the buffer) so that they can be manipulated more easily.

Add the following lines that set up up a FileReader and a BufferedReader:

A FileReader  and BufferedReader

We're creating two new objects here: 1 is a FileReader object which nosotros've called fr; the other is a BufferedReader object with the proper noun textReader.

The FileReader needs the name of file to open up. For us, the file path and name is held in the field variable chosen path. So nosotros can use this.

The BufferedReader is handed the FileReader object between its round brackets. All the characters from the file are then held in memory waiting to be manipulated. They are held under the variable proper noun textReader.

Before we tin read the lines of text, nosotros need to set up an array. Each position in the assortment can and then agree i complete line of text. So add the post-obit two lines to your lawmaking:

int numberOfLines = 3;
String[ ] textData = new String[numberOfLines];

For now, nosotros'll set the number of lines in the text file to just 3. Obviously, text files tin concord any number of lines, and nosotros normally don't know how many. So we'll modify this presently. Nosotros'll write a divide method that gets the number of lines in a text file.

The second line of new code, though, sets up a String assortment. The number of positions in the array (its size) is set to the number of lines. We've put this betwixt the foursquare brackets.

To put all the lines of text from the file into each position in the array, we need a loop. The loop will get each line of text and place each line into the assortment. Add the following to your code:

int i;

for (i=0; i < numberOfLines; i++) {
textData[ i ] = textReader.readLine();

}

Your coding window should now look like this:

Looping through the text file

The for loop goes from 0 to but less than the number of lines. (Array positions, retrieve, start at 0. The three lines will be stored at positions 0, 1, and 2.)

The line that accesses the lines of text and stores them in the assortment is this ane:

textData[i] = textReader.readLine( );

After the equals sign we have this:

textReader.readLine( );

The textReader object we set up is holding all the characters from the text file in memory (the buffer). Nosotros can utilize the readLine method to read a complete line from the buffer. After the line is read, we shop the line in an assortment position:

textData[i]

The variable called i will increment each time round the loop, thus going through the entire array storing lines of text.

Only 2 more lines of code to add together to the method, now. So add together these lines to your lawmaking:

textReader.close( );
return textData;

The close method flushes the temporary memory buffer called textReader. The return line returns the whole array. Notice that no foursquare brackets are needed for the assortment name.

When y'all've added the lawmaking, all those ugly underlines should disappear. Your method should then look similar this:

Closing the BufferedReader

At that place'south still the trouble of the number of lines, however. We've hard-coded this to iii. What we need is to go through any text file and count how many lines it has. So add the following method to your ReadFile grade:

A method to read lines of text

The new method is called readLines, and is set to return an integer value. This is the number of lines a text file has. Discover this method also has an IOException part to the method header.

The code for the method sets up another FileReader, and another BufferedReader. To loop round the lines of text, we accept this:

while ( ( aLine = bf.readLine( ) ) != nada ) {
numberOfLines++;
}

The while loop looks a chip messy. But information technology but says "read each line of text and end when a null value is reached." (If at that place's no more lines in a text file, Java returns a value of null.) Inside the curly brackets, we increment a counter called numberOfLines.

The final 2 lines of code affluent the retention buffer called bf, and returns the number of lines.

To call this new method into action, change this line in your OpenFile method:

int numberOfLines = 3;

Change it to this:

int numberOfLines = readLines( );

So instead of hard-coding the number of lines, we can call our new method and become the number of lines in any text file.

OK, time to put the new form to piece of work and see if it opens a text file.

Get dorsum to your FileData class, the one with the primary method in information technology. Set upward a string variable to hold the name of a text file:

A FilePath added to Main

At this stage, you need to create a text file somewhere on your computer. We created this simple 1 in Notepad on a Windows machine:

The name of the text file is "test.txt". Create a like text file on your own estimator. Note where yous saved it to because you demand the file path as well:

String file_name = "C:/examination.txt";

And then our test.txt file is saved on the C bulldoze. If we had created a folder chosen MyFiles to hold the file so the path would be "C:/MyFiles/test.txt". Alter yous file path, if need exist.

The next affair to practice is to create a new object from our ReadFile course. Nosotros can then phone call the method that opens the file. But we can do this in a effort … take hold of block. Add the following lawmaking, just below your Cord variable line:

Creating a new ReadFile object

Don't forget all the curly brackets for the try … catch block. You demand one pair for the endeavor part and another pair for the catch part. For the try part, we have this:

ReadFile file = new ReadFile( file_name );
String[ ] aryLines = file.OpenFile( );

The first line sets upwardly a new ReadFile object called file. In between the round brackets of ReadFile, we added the file_name variable. This is enough to paw the constructor the file path it needs.

The second line of code sets upwardly a Cord assortment chosen aryLines. Later the equals sign, we've chosen the OpenFile method of our ReadFile class. If it successfully opens up the text file, then the array of text lines will exist handed over to the new array aryLines.

If something goes wrong, withal, an fault is thrown up the line, and ends upward in the catch part of the try … catch block:

catch ( IOException e ) {
Organization.out.println( e.getMessage() );
}

Later the word "catch" nosotros have a pair of circular brackets. Inside the round brackets, nosotros have this:

IOException e

What this does is to set a variable chosen due east which is of type IOException. The IOException object has methods of its own that you can use. One of these methods is getMessage. This will give the user some information on what went incorrect.

Before nosotros see an example of an error message, let's loop through all the lines of the text file, printing out each 1. Add the post-obit loop lawmaking to the try part of the endeavor … catch block:

int i;
for ( i=0; i < aryLines.length; i++ ) {
Organisation.out.println( aryLines[ i ] ) ;
}

Your coding window should at present expect like this:

Printing out each line from the text file

When the programme is run, the Output window will impress the following:

The Open File Output

As you lot can see, each line from our text file has been printed out.

To test the error checking function of the lawmaking, modify the name of your text file to one you lot know has not been created. And so run your code again. In the Output window below, y'all can see that our text file was changed to testB, and that it couldn't exist found:

Exception error

If you prefer, yous can add your own error message to the catch block:

An error message

Output window 2

It'southward probably amend to leave it to Java, though!

In the next part, y'all'll learn how to write to a text file using Java code.

<-- Logic Errors | Write to a Text File -->

Dorsum to the Java Contents Page

izzovate2001.blogspot.com

Source: https://www.homeandlearn.co.uk/java/read_a_textfile_in_java.html

0 Response to "Java Read File With Hard Return on Line"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel