How to Read a Text File in Java Using Eclipse
The Coffee IO API provides ii kinds of interfaces for reading files, streams and readers. The streams are used to read binary information and readers to read character information. Since a text file is full of characters, y'all should be using a Reader implementations to read it. There are several ways to read a plain text file in Coffee e.yard. you lot can use FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
You can also use both BufferedReader and Scanner to read a text file line past line in Java. Then Java SE 8 introduces another Stream grade java.util.stream.Stream which provides a lazy and more than efficient mode to read a file.
The JDK 7 also introduces a couple of nice utility e.one thousand. Files class and try-with-resource construct which made reading a text file, even more, easier.
In this commodity, I am going to share a couple of examples of reading a text file in Coffee with their pros, cons, and important points about each approach. This will give you enough detail to choose the right tool for the chore depending on the size of file, the content of the file, and how you desire to read.
1. Reading a text file using FileReader
The FileReader is your full general-purpose Reader implementation to read a file. It accepts a Cord path to file or a coffee.io.File case to beginning reading. It also provides a couple of overloaded read() methods to read a character or read characters into an array or into a CharBuffer object.
Here is an example of reading a text file using FileReader in Java:
public static void readTextFileUsingFileReader(String fileName) { try { FileReader textFileReader = new FileReader(fileName); char[] buffer = new char[8096]; int numberOfCharsRead = textFileReader.read(buffer); while (numberOfCharsRead ! = -ane) { System.out.println(String.valueOf(buffer, 0, numberOfCharsRead)); numberOfCharsRead = textFileReader.read(buffer); } textFileReader.shut(); } catch (IOException e) { // TODO Automobile-generated grab block e.printStackTrace(); } } Output Once upon a time, nosotros wrote a plan to read data from a text file. The plan failed to read a big file but and so Java eight come up to rescue, which made reading file lazily using Streams.
You can see that instead of reading ane character at a time, I am reading characters into an array. This is more than efficient because read() will access the file several times simply read(char[]) will access the file just one time to read the aforementioned corporeality of data.
I am using an 8KB of the buffer, then in one call I am express to read that much data only. You tin can have a bigger or smaller buffer depending upon your heap retentiveness and file size. You should likewise notice that I am looping until read(char[]) returns -ane which signals the end of the file.
Another interesting thing to note is to call to Cord.valueOf(buffer, 0, numberOfCharsRead), which is required because you might not have 8KB of data in the file or even with a bigger file, the last telephone call may non exist able to fill the char array and it could contain muddied information from the last read.
two. Reading a text file in Java using BufferedReader
The BufferedReader grade is a Decorator which provides buffering functionality to FileReader or any other Reader. This class buffer input from source e.g. files into retention for the efficient read. In the case of BufferedReader, the telephone call to read() doesn't e'er goes to file if it can find the data in the internal buffer of BufferedReader.
The default size of the internal buffer is 8KB which is expert enough for well-nigh purpose, only you can also increment or decrease buffer size while creating BufferedReader object. The reading code is similar to the previous example.
public static void readTextFileUsingBufferdReader(String fileName) { endeavour { FileReader textFileReader = new FileReader(fileName); BufferedReader bufReader = new BufferedReader(textFileReader); char[] buffer = new char[8096]; int numberOfCharsRead = bufReader.read(buffer); // read volition be from // retentiveness while (numberOfCharsRead ! = -i) { System.out.println(String.valueOf(buffer, 0, numberOfCharsRead)); numberOfCharsRead = textFileReader.read(buffer); } bufReader.close(); } catch (IOException e) { // TODO Auto-generated grab block east.printStackTrace(); } } Output [From File] Java provides several ways to read file
In this example as well, I am reading the content of the file into an array. Instead of reading one character at a time, this is more efficient. The merely difference between the previous examples and this one is that the read() method of BufferedReader is faster than theread() method of FileReader because read can happen from memory itself.
In order to read the full-text file, you loop until read(char[]) method returns -one, which signals the end of the file. Encounter Core Java Book 1 - Fundamentals to learn more almost how BufferedReader class works in Java.
iii. Reading a text file in Java using Scanner
The third tool or class to read a text file in Java is the Scanner, which was added on JDK 1.5 release. The other two FileReader and BufferedReader are present from JDK 1.0 and JDK i.1 versions. The Scanner is a much more than characteristic-rich and versatile class.
It does not but provide reading just the parsing of data every bit well. You can non only read text data but you can also read the text equally a number or float using nextInt() and nextFloat() methods.
The class uses regular expression pattern to determine token, which could be tricky for newcomers. The two master method to read text data from Scanner is next() and nextLine(), sometime one read words separated by space while later one can be used to read a text file line by line in Java. In most cases, you would apply the nextLine() method as shown beneath:
public static void readTextFileUsingScanner(String fileName) { try { Scanner sc = new Scanner(new File(fileName)); while (sc.hasNext()) { String str = sc.nextLine(); System.out.println(str); } sc.close(); } catch (IOException east) { // TODO Auto-generated catch block e.printStackTrace(); } } Output [From File] Coffee provides several ways to read the file.
You tin can use the hasNext() method to determine if there is whatsoever more token left to read in the file and loop until it returns false. Though you should call up that next() or nextLine() may block until data is bachelor fifty-fifty if hasNext() return truthful. This code is reading the content of "file.txt" line by line. Meet this tutorial to learn more about the Scanner grade and file reading in Java.
4. Reading a text file using Stream in Coffee viii
The JDK eight release has brought some cool new features e.g. lambda expression and streams which brand file reading even smoother in Coffee. Since streams are lazy, y'all tin can use them to read-only lines you want from the file east.m. yous tin can read all non-empty lines by filtering empty lines. The employ of method reference also makes the file reading code much more unproblematic and concise, and so much and then that you can read a file in just one line equally shown beneath:
Files.lines(Paths.get("newfile.txt")).forEach(System.out: :println); Output This is the get-go line of file something is better than zip this is the terminal line of the file
Now, if you lot desire to do some pre-processing, here is code to trim each line, filter empty lines to merely read non-empty ones, and remember, this is lazy because Files.lines() method return a stream of Cord and Streams are lazy in JDK 8 (see Java 8 in Activity).
Files.lines(new File("newfile.txt").toPath()) .map(s -> s.trim()) .filter(south -> !s.isEmpty()) .forEach(System.out: :println);
We'll use this code to read a file that contains a line that is total of whitespace and an empty line, the same ane which nosotros have used in the previous case, but this time, the output will not contain 5 line but just three lines because empty lines are already filtered, as shown below:
Output This is the first line of file something is better than nothing this is the terminal line of the file
You can see merely three out of five lines appeared because the other two got filtered. This is simply the tip of the iceberg on what you can exercise with Java SE viii, See Java SE viii for Really Impatient to larn more near Java 8 features.
v. How to read a text file equally Cord in Coffee
Sometimes yous read the full content of a text file as Cord in Java. This is mostly the case with small text files as for large files you volition face java.lang.OutOfMemoryError: java heap space error. Prior to Java 7, this requires a lot of boiler code because you need to utilise a BufferedReader to read a text file line by line then add together all those lines into a StringBuilder and finally return the String generated from that.
Now y'all don't need to do all that, you can use the Files.readAllBytes() method to read all bytes of the file in i shot. In one case done that yous tin can convert that byte array into Cord. every bit shown in the following example:
public static String readFileAsString(Cord fileName) { String data = ""; try { data = new String(Files.readAllBytes(Paths.get("file.txt"))); } take hold of (IOException e) { e.printStackTrace(); } render information; } Output [From File] Coffee provides several ways to read file
This was a rather pocket-sized file so information technology was pretty easy. Though, while using readAllBytes() yous should remember grapheme encoding. If your file is not in platform's default character encoding then you must specify the graphic symbol doing explicitly both while reading and converting to Cord. Utilize the overloaded version of readAllBytes() which accepts character encoding. You lot tin also come across how I read XML as String in Java here.
6. Reading the whole file in a List
Similar to the last example, sometimes you need all lines of the text file into an ArrayList or Vector or merely on a List. Prior to Java 7, this job besides involves boilerplate east.g. reading files line past line, calculation them into a list, and finally returning the list to the caller, but later on Java 7, it's very elementary now. You but need to use the Files.readAllLines() method, which returns all lines of the text file into a List, as shown below:
public static List<String> readFileInList(String fileName) { List<Cord> lines = Collections.emptyList(); try { lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8); } take hold of (IOException e) { // TODO Machine-generated catch block due east.printStackTrace(); } return lines; }
Similar to the terminal example, y'all should specify character encoding if it's unlike from than platform's default encoding. You tin use see I have specified UTF-eight here. Again, utilize this trick only if you lot know that file is small and you take enough memory to hold a Listing containing all lines of the text file, otherwise your Java program volition crash with OutOfMemoryError.
7. How to read a text file in Java into an array
This example is besides very similar to the last two examples, this time, we are reading the contents of the file into a String assortment. I have used a shortcut here, first, I have read all the lines as List and then converted the listing to an assortment.
This results in simple and elegant code, but yous can besides read information into a grapheme array equally shown in the start example. Employ the read(char[] data) method while reading data into a grapheme assortment.
Here is an example of reading a text file into String array in Coffee:
public static Cord[] readFileIntoArray(String fileName) { List<String> list = readFileInList(fileName); render list.toArray(new String[listing.size()]); }
This method leverage our existing method which reads the file into a List and the code hither is only to convert a listing to an array in Coffee.
8. How to read a file line by line in Java
This is one of the interesting examples of reading a text file in Java. You frequently need file information as line past line. Fortunately, both BufferedReader and Scanner provide convenient utility method to read line by line. If y'all are using BufferedReader so you lot can use readLine() and if yous are using Scanner then you can utilize nextLine() to read file contents line by line. In our case, I accept used BufferedReader as shown below:
public static void readFileLineByLine(Cord fileName) { attempt (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line = br.readLine(); while (line ! = null) { System.out.println(line); line = br.readLine(); } } grab (IOException e) { e.printStackTrace(); } }
Just remember that A line is considered to exist terminated past whatsoever i of a line feed ('\north'), a carriage return ('\r'), or a carriage render followed immediately by a line feed.
Java Program to read a text file in Coffee
Here is the consummate Java plan to read a obviously text file in Java. Yous can run this plan in Eclipse provided you lot create the files used in this program due east.g. "sample.txt", "file.txt", and "newfile.txt". Since I am using a relative path, yous must ensure that files are in the classpath. If yous are running this program in Eclipse, you can merely create these files in the root of the project directory. The plan will throw FileNotFoundException or NoSuchFileExcpetion if it is not able to find the files.
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import coffee.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import coffee.util.Collections; import java.util.List; import java.util.Scanner; /* * Java Programme read a text file in multiple way. * This program demonstrate how you tin can use FileReader, * BufferedReader, and Scanner to read text file, * forth with newer utility methods added in JDK seven * and 8. */ public class FileReadingDemo { public static void primary(String[] args) throws Exception { // Example 1 - reading a text file using FileReader in Java readTextFileUsingFileReader("sample.txt"); // Example 2 - reading a text file in Java using BufferedReader readTextFileUsingBufferdReader("file.txt"); // Example iii - reading a text file in Java using Scanner readTextFileUsingScanner("file.txt"); // Case 4 - reading a text file using Stream in Coffee viii Files.lines(Paths.become("newfile.txt")).forEach(System.out: :println); // Example five - filtering empty lines from a file in Java eight Files.lines(new File("newfile.txt").toPath()) .map(s -> s.trim()) .filter(due south -> !south.isEmpty()) .forEach(System.out: :println); // Example 6 - reading a text file as String in Java readFileAsString("file.txt"); // Example vii - reading whole file in a List Listing<String> lines = readFileInList("newfile.txt"); Arrangement.out.println("Full number of lines in file: " + lines.size()); // Example viii - how to read a text file in java into an array String[] arrayOfString = readFileIntoArray("newFile.txt"); for(String line: arrayOfString){ System.out.println(line); } // Case ix - how to read a text file in java line by line readFileLineByLine("newFile.txt"); // Example ten - how to read a text file in java using eclipse // all examples y'all can run in Eclipse, at that place is nothing special about it. } public static void readTextFileUsingFileReader(Cord fileName) { try { FileReader textFileReader = new FileReader(fileName); char[] buffer = new char[8096]; int numberOfCharsRead = textFileReader.read(buffer); while (numberOfCharsRead ! = -1) { System.out.println(Cord.valueOf(buffer, 0, numberOfCharsRead)); numberOfCharsRead = textFileReader.read(buffer); } textFileReader.close(); } catch (IOException eastward) { // TODO Auto-generated catch cake e.printStackTrace(); } } public static void readTextFileUsingBufferdReader(String fileName) { try { FileReader textFileReader = new FileReader(fileName); BufferedReader bufReader = new BufferedReader(textFileReader); char[] buffer = new char[8096]; int numberOfCharsRead = bufReader.read(buffer); // read will exist from // retention while (numberOfCharsRead ! = -1) { Organisation.out.println(String.valueOf(buffer, 0, numberOfCharsRead)); numberOfCharsRead = textFileReader.read(buffer); } bufReader.close(); } catch (IOException e) { // TODO Automobile-generated catch block e.printStackTrace(); } } public static void readTextFileUsingScanner(String fileName) { try { Scanner sc = new Scanner(new File(fileName)); while (sc.hasNext()) { String str = sc.nextLine(); System.out.println(str); } sc.close(); } catch (IOException eastward) { // TODO Auto-generated grab block e.printStackTrace(); } } public static String readFileAsString(Cord fileName) { String data = ""; endeavour { information = new String(Files.readAllBytes(Paths.get("file.txt"))); } catch (IOException e) { e.printStackTrace(); } render data; } public static Listing<String> readFileInList(String fileName) { List<Cord> lines = Collections.emptyList(); endeavour { lines = Files.readAllLines(Paths.go("file.txt"), StandardCharsets.UTF_8); } grab (IOException e) { // TODO Car-generated catch cake e.printStackTrace(); } return lines; } public static String[] readFileIntoArray(String fileName) { List<String> listing = readFileInList(fileName); return list.toArray(new String[listing.size()]); } public static void readFileLineByLine(String fileName) { effort (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line = br.readLine(); while (line ! = null) { System.out.println(line); line = br.readLine(); } } take hold of (IOException e) { due east.printStackTrace(); } } }
I take not printed the output here because we have already gone through that and talk over in corresponding examples, but you lot need Java eight to compile and run this program. If you are running on Coffee vii, and so just remove the example 4 and 5 which uses Java eight syntax and features and the program should run fine.
That'south all nigh how to read a text file in Java. We have looked at all major utilities and classes which you can utilize to read a file in Java likeFileReader, BufferedReader, and Scanner. We have also looked at utility methods added on Java NIO 2 on JDK seven like. Files.readAllLines() and Files.readAllBytes() to read the file in List and Cord respectively.
Other Java File tutorials for beginners
- How to bank check if a File is hidden in Java? (solution)
- How to read an XML file in Java? (guide)
- How to read an Excel file in Java? (guide)
- How to read an XML file as String in Java? (example)
- How to re-create non-empty directories in Java? (example)
- How to read/write from/to RandomAccessFile in Java? (tutorial)
- How to append text to a File in Java? (solution)
- How to read a ZIP file in Coffee? (tutorial)
- How to read from a Retentiveness Mapped file in Java? (example)
Finally, we accept besides touched new style of file reading with Java 8 Stream, which provides lazy reading and the useful pre-processing option to filter unnecessary lines.
kennedybobjection.blogspot.com
Source: https://javarevisited.blogspot.com/2016/07/10-examples-to-read-text-file-in-java.html
0 Response to "How to Read a Text File in Java Using Eclipse"
Post a Comment