This page will teach you about reading from text files in Java.
What is used for reading from text files?
There are many ways to read from text files in Java but the way I will talk about is using BufferedReader with FileReaders. Because of this we need to import two namespaces as well as two extra namespaces used for separate exceptions;
To read from a file we first need the file path of the text file as a string, we need the four imports listed above, and you will also need knowledge of Try and Catch statements, as well as Do While statements.
The first thing we need to do is create a simple Try and Catch statement:
The statement throws a FileNotFoundException (which pretty simple and self-explanatory) but it handles the error if the file is not found that is trying to be read by the program. Now we need to create a BufferedReader from a FileReader of the text file path (this will essentially just grab the file for use)...
Next we want to create a new String variable and initiate it as a blank String (to avoid an error) and then we want to read each line of the BufferedReader text file and add each line to the "line" string variable. This will be done through a Do While statement...
This is also encased in a Try and Catch statement (IO Exception) just in case there is a problem with the file (a line is blank etc). Here is the full source...
line += br.readLine();
}while (br.readLine() != null);
Which gives the output which is contained in our "read.txt" file:
This is our read text file.