Reading Lines of Txt File in Java and Storing as String
Manipulating text files is a skill that will serve you well in your programming career. In this section, you'll larn how to open up and how to write to a text file. But by text file, we merely mean a file with text in information technology - uncomplicated as that! You tin can create a text file in programmes like Notepad on a Windows computer, TextEdit on a Mac, Gedit in a Linux/Gnome surroundings.
The showtime thing we'll practice is to open up a text file and read its contents.
Reading a Text File
Kickoff a new projection for this. Call the package textfiles and the form FileData. Add an import statement just below the packet line and earlier the class name:
import coffee.io.IOException;
Your coding window volition so look like this:
To deal with anything going incorrect with our file handling, add the following to the chief method (the text in bold):
public static void chief(String[ ] args) throws IOException {
}
We're telling Coffee that the main method volition throw upward an IOException mistake, and that it has to exist dealt with. Later, we'll add together a try … catch block to brandish an appropriate error message for the user, should something get wrong.
To open the text file, let's create a new class. So click File > New File from the NetBeans card at the pinnacle. Create a new Java Class file and give information technology the name ReadFile. When your new grade is created, add together the following iii import statements:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
Your new grade should then look similar this one:
(The import lines are underlined because nosotros haven't done anything with them yet. This is a NetBeans feature.)
We'll create a new object from this form to read a file. Add the post-obit constructor to your code, along with the private String field chosen path:
All we're doing here is passing in the name of a file, and so handing the file name over to the path field.
What we now need to practice is create a method that returns all the lines of code from the text file. The lines volition exist held in an array. Add the following method proclamation that will open up the file:
Don't worry about the red underline: it will go abroad once we've added some code. NetBeans has just added it because we have no render statement.
Discover that the method is fix to render a Cord assortment, though:
public Cord[ ]
The assortment will contain all the lines from the text file.
Observe, too, 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. Java will throw any errors up the line, and they will be caught in our chief method.
To read characters from a text file, the FileReader is used. This reads bytes from a text file, and each byte is a single graphic symbol. You can read whole lines of text, rather than single characters. To do this, y'all tin can hand your FileReader over to something called a BufferedReader. The BufferedReader has a handy method chosen ReadLine. Every bit its proper noun suggests, information technology is used to read whole lines, rather than single characters. What the BufferedReader does, though, is to shop characters in memory (the buffer) so that they can be manipulated more hands.
Add the following lines that prepare a FileReader and a BufferedReader:
Nosotros're creating ii new objects hither: ane is a FileReader object which we've called fr; the other is a BufferedReader object with the name textReader.
The FileReader needs the name of file to open. For united states of america, the file path and name is held in the field variable called path. So we tin use this.
The BufferedReader is handed the FileReader object between its round brackets. All the characters from the file are so held in memory waiting to be manipulated. They are held nether the variable name textReader.
Before nosotros can read the lines of text, we demand to prepare upward an array. Each position in the array can then agree one complete line of text. And then add together the following two lines to your code:
int numberOfLines = 3;
String[ ] textData = new String[numberOfLines];
For at present, nosotros'll fix the number of lines in the text file to just 3. Obviously, text files can hold whatsoever number of lines, and we usually don't know how many. So we'll change this before long. We'll write a dissever method that gets the number of lines in a text file.
The 2d line of new code, though, sets up a String array. The number of positions in the assortment (its size) is fix to the number of lines. We've put this between the square 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 together the following to your code:
int i;
for (i=0; i < numberOfLines; i++) {
textData[ i ] = textReader.readLine();
}
Your coding window should at present look like this:
The for loop goes from 0 to just less than the number of lines. (Array positions, recall, start at 0. The 3 lines volition be stored at positions 0, 1, and 2.)
The line that accesses the lines of text and stores them in the array is this one:
textData[i] = textReader.readLine( );
Later the equals sign we have this:
textReader.readLine( );
The textReader object nosotros set is holding all the characters from the text file in memory (the buffer). We can use the readLine method to read a complete line from the buffer. Afterward the line is read, we store the line in an array position:
textData[i]
The variable chosen i will increment each time round the loop, thus going through the entire array storing lines of text.
Only two more than lines of code to add together to the method, now. And then add these lines to your lawmaking:
textReader.close( );
return textData;
The close method flushes the temporary memory buffer called textReader. The render line returns the whole array. Notice that no square brackets are needed for the array proper name.
When yous've added the lawmaking, all those ugly underlines should disappear. Your method should then look similar this:
There'due south still the problem of the number of lines, however. We've hard-coded this to 3. What we need is to go through any text file and count how many lines it has. So add the post-obit method to your ReadFile course:
The new method is called readLines, and is gear up to render an integer value. This is the number of lines a text file has. Observe 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, nosotros have this:
while ( ( aLine = bf.readLine( ) ) != null ) {
numberOfLines++;
}
The while loop looks a fleck messy. But information technology just says "read each line of text and end when a null value is reached." (If there'southward no more than lines in a text file, Java returns a value of null.) Inside the curly brackets, we increase a counter called numberOfLines.
The final two lines of code flush the retention buffer called bf, and returns the number of lines.
To call this new method into action, alter this line in your OpenFile method:
int numberOfLines = 3;
Modify it to this:
int numberOfLines = readLines( );
And so instead of hard-coding the number of lines, we tin can telephone call our new method and get 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.
Go dorsum to your FileData class, the one with the chief method in it. Set up a string variable to hold the name of a text file:
At this stage, you need to create a text file somewhere on your computer. We created this simple ane in Notepad on a Windows car:
The proper noun of the text file is "test.txt". Create a similar text file on your ain calculator. Note where you saved it to considering you demand the file path as well:
String file_name = "C:/test.txt";
So our exam.txt file is saved on the C drive. If we had created a folder called MyFiles to hold the file so the path would exist "C:/MyFiles/examination.txt". Alter you file path, if need be.
The adjacent thing to do is to create a new object from our ReadFile class. We tin and so call the method that opens the file. But we can do this in a try … take hold of block. Add the following code, simply below your Cord variable line:
Don't forget all the curly brackets for the effort … catch cake. You lot need 1 pair for the attempt part and another pair for the catch part. For the try role, we have this:
ReadFile file = new ReadFile( file_name );
String[ ] aryLines = file.OpenFile( );
The first line sets up a new ReadFile object chosen file. In between the round brackets of ReadFile, we added the file_name variable. This is enough to mitt the constructor the file path it needs.
The 2d line of lawmaking sets up a String assortment chosen aryLines. After the equals sign, we've chosen the OpenFile method of our ReadFile grade. If it successfully opens up the text file, and so the array of text lines will be handed over to the new array aryLines.
If something goes incorrect, however, an error is thrown upwardly the line, and ends up in the catch part of the try … catch block:
catch ( IOException e ) {
System.out.println( e.getMessage() );
}
Later the word "grab" we have a pair of circular brackets. Within the round brackets, we have this:
IOException eastward
What this does is to prepare a variable called e 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 wrong.
Earlier we come across an example of an error message, let's loop through all the lines of the text file, printing out each one. Add the following loop code to the try part of the effort … take hold of cake:
int i;
for ( i=0; i < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
Your coding window should now look like this:
When the programme is run, the Output window will print the following:
As y'all can run into, each line from our text file has been printed out.
To test the error checking part of the code, change the proper name of your text file to one you lot know has not been created. Then run your code again. In the Output window below, you lot can see that our text file was changed to testB, and that information technology couldn't be found:
If you adopt, you tin add your ain error message to the catch block:
It's probably better to leave it to Java, though!
In the side by side office, you'll learn how to write to a text file using Java code.
<-- Logic Errors | Write to a Text File -->
Back to the Java Contents Folio
Source: https://www.homeandlearn.co.uk/java/read_a_textfile_in_java.html
0 Response to "Reading Lines of Txt File in Java and Storing as String"
Enregistrer un commentaire