There are multiple ways to read a file inwards Java e.g. y'all tin utilisation a Scanner equally nosotros accept seen inwards the last example, or y'all tin utilisation the BufferedReader class. The wages of using a BufferedReader to read a text file is speed. It allows faster reading because of internal buffering provided yesteryear BufferedReader. Other Reader classes e.g. FileReader access the file or disk everytime y'all telephone band the read() method but BufferedReader keeps 8KB worth of information inwards its internal buffer which y'all tin read it without accessing file multiple times. It's loaded when y'all access the file outset fourth dimension for a subsequent read. The BufferedReader degree is too a practiced instance of Decorator pattern pattern because it decorates existing readers e.g. FileReader to supply buffering, remember, the reading from file functionality withal comes from the FileReader class.
One to a greater extent than wages of using the BufferedReader for reading a text file is its powerfulness to read file trouble yesteryear line. It provides a readLine() method which tin live used to read a text file trouble yesteryear line inwards Java.
The java.io.BufferedReader degree provides four versions of the read() method to read information from a text file
read() - to read a unmarried character, this method render an int, hence y'all necessitate to cast that to a character
read(char[] cbuf) - to read characters into an array. This method volition block until unopen to input is available, an I/O fault occurs, or the destination of the current is reached. This method either render publish of characters read or -1 if the destination of file has been reached. The method comes from the Reader class.
read(CharBuffer cbuffer) - to read characters into a CharBuffer, this is similar to the previous method except that it reads characters into a CharBuffer object instead of the array. This method too returns a amount publish of characters read or -1 if the destination of file has been reached. This method too belongs to java.io.Reader class.
read(char[] cbuf, int off, int len) - to read characters into an array but gives y'all command where to shop the characters read from a file. You tin specify offset i.e. the indices to start too length, how many characters to store.
readLine() - to read a Line of text. You tin utilisation this method to read a file trouble yesteryear trouble inwards Java. Influenza A virus subtype H5N1 trouble is considered to live terminated yesteryear whatever 1 of a trouble feed ('\n'), a railroad vehicle render ('\r'), or a railroad vehicle render followed at 1 time yesteryear a linefeed. This method returns a String containing the contents of the line, non including whatever line-termination characters, or cypher if the destination of the current has been reached. Many Java developer uses BufferedReader degree only for this method.
Btw, from Java 8 onwards in that place are many ways to read a file trouble yesteryear trouble inwards Java e.g. y'all tin utilisation Files.lines() method to acquire all lines equally Stream inwards Java too and then y'all cannot solely read them trouble yesteryear trouble but too y'all tin too utilisation Stream operations e.g. map(), flatMap(), filter() etc to perform useful operations.
If y'all are non familiar amongst functional programming too Java 8 run into Java SE 8 for Really impatient to larn to a greater extent than almost basics of functional programming amongst Java 8 syntax.
If y'all notice carefully, spell converting the grapheme array to String, nosotros accept correctly used the offset too length because it mightiness live possible that the array which y'all are using for storing content, may content dingy information from the previous read, equally nosotros are non cleaning it upwards subsequently every read. That's the wages of using offset too length, y'all don't necessitate to clear or laid clean the array. See Core Java Volume 1 - Fundamentals to larn to a greater extent than almost file reading inwards Java.
Java BufferedReader Example
You tin run into from the output that nosotros accept successfully read the text file. In the minute example, since nosotros accept used the try-with-resource construct, y'all don't necessitate to manually telephone band the close() method of BufferedReader, it volition automatically live called yesteryear Java. The grab clause is in that place to grab the IOException thrown yesteryear the close() method.
That's all almost how to read a text file using BufferedReader inwards Java. As I said, in that place are 2 principal reasons to utilisation the BufferedReader class, outset the buffering it provides which makes reading efficient, too minute the readLine() method it gives, which allows y'all to read the text file trouble yesteryear line. If y'all running inwards Java 8, y'all tin too utilisation streams to lazily read the file content yesteryear using Files.lines() method which returns a Stream of String from a text file. You tin too then perform operations similar map() too filter() on file content.
One to a greater extent than wages of using the BufferedReader for reading a text file is its powerfulness to read file trouble yesteryear line. It provides a readLine() method which tin live used to read a text file trouble yesteryear line inwards Java.
The java.io.BufferedReader degree provides four versions of the read() method to read information from a text file
read() - to read a unmarried character, this method render an int, hence y'all necessitate to cast that to a character
read(char[] cbuf) - to read characters into an array. This method volition block until unopen to input is available, an I/O fault occurs, or the destination of the current is reached. This method either render publish of characters read or -1 if the destination of file has been reached. The method comes from the Reader class.
read(CharBuffer cbuffer) - to read characters into a CharBuffer, this is similar to the previous method except that it reads characters into a CharBuffer object instead of the array. This method too returns a amount publish of characters read or -1 if the destination of file has been reached. This method too belongs to java.io.Reader class.
read(char[] cbuf, int off, int len) - to read characters into an array but gives y'all command where to shop the characters read from a file. You tin specify offset i.e. the indices to start too length, how many characters to store.
readLine() - to read a Line of text. You tin utilisation this method to read a file trouble yesteryear trouble inwards Java. Influenza A virus subtype H5N1 trouble is considered to live terminated yesteryear whatever 1 of a trouble feed ('\n'), a railroad vehicle render ('\r'), or a railroad vehicle render followed at 1 time yesteryear a linefeed. This method returns a String containing the contents of the line, non including whatever line-termination characters, or cypher if the destination of the current has been reached. Many Java developer uses BufferedReader degree only for this method.
Btw, from Java 8 onwards in that place are many ways to read a file trouble yesteryear trouble inwards Java e.g. y'all tin utilisation Files.lines() method to acquire all lines equally Stream inwards Java too and then y'all cannot solely read them trouble yesteryear trouble but too y'all tin too utilisation Stream operations e.g. map(), flatMap(), filter() etc to perform useful operations.
If y'all are non familiar amongst functional programming too Java 8 run into Java SE 8 for Really impatient to larn to a greater extent than almost basics of functional programming amongst Java 8 syntax.
Java Program to read a text file using BufferedReader
Here is our sample Java plan to read a patently text file using BufferedReader. In this program, I accept shown 2 examples of BufferedReader class, the outset 1 reads file content into a character array too the minute 1 reads the text file trouble yesteryear line.If y'all notice carefully, spell converting the grapheme array to String, nosotros accept correctly used the offset too length because it mightiness live possible that the array which y'all are using for storing content, may content dingy information from the previous read, equally nosotros are non cleaning it upwards subsequently every read. That's the wages of using offset too length, y'all don't necessitate to clear or laid clean the array. See Core Java Volume 1 - Fundamentals to larn to a greater extent than almost file reading inwards Java.
Java BufferedReader Example
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /* * Java Program read a text file using BufferedReader. * It allows y'all to read file trouble yesteryear trouble or straight * into a grapheme array. */ public class BufferedReaderDemo { public static void main(String[] args) throws Exception { String filename = "newfile.txt"; // reading text file into array try { FileReader textFileReader = new FileReader(filename); BufferedReader bufReader = new BufferedReader(textFileReader); char[] buffer = new char[8096]; int numberOfCharsRead = bufReader.read(buffer); // read volition live from // memory while (numberOfCharsRead != -1) { System.out.println(String.valueOf(buffer, 0, numberOfCharsRead)); numberOfCharsRead = textFileReader.read(buffer); } bufReader.close(); } catch (IOException e) { // TODO Auto-generated grab block e.printStackTrace(); } // reading file trouble yesteryear trouble using BufferedReader try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String trouble = br.readLine(); while (line != null) { System.out.println(line); trouble = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } } Output [first line] hullo [second line] cheerio [first line] hullo [second line] bye
You tin run into from the output that nosotros accept successfully read the text file. In the minute example, since nosotros accept used the try-with-resource construct, y'all don't necessitate to manually telephone band the close() method of BufferedReader, it volition automatically live called yesteryear Java. The grab clause is in that place to grab the IOException thrown yesteryear the close() method.
That's all almost how to read a text file using BufferedReader inwards Java. As I said, in that place are 2 principal reasons to utilisation the BufferedReader class, outset the buffering it provides which makes reading efficient, too minute the readLine() method it gives, which allows y'all to read the text file trouble yesteryear line. If y'all running inwards Java 8, y'all tin too utilisation streams to lazily read the file content yesteryear using Files.lines() method which returns a Stream of String from a text file. You tin too then perform operations similar map() too filter() on file content.
Related Java File tutorials y'all may like
- How to write to a file using BufferedWriter inwards Java? (solution)
- How to append text to a file inwards Java? (solution)
- 2 ways to read a text file inwards Java? (solution)
- How to read InputStream equally Stream inwards Java? (example)
- How to charge information from a CSV file inwards Java? (example)
- How to notice the highest occurring give-and-take from a file inwards Java? (solution)
- How to read/write an XLSX file inwards Java? (solution)
References


0 Response to "How to read a text file inwards Java - BufferedReader Example"
Posting Komentar