How to Write a Loop About Reading a File in Java
You can read a text file in Coffee 6 by using BufferedReader or Scanner class. Both classes provide convenient methods to read a text file line by line eastward.chiliad. Scanner provides nextLine() method and BufferedReader provides readLine() method. If you lot are reading a binary file, you can useFileInputStream. Past the way, when you are reading text data, you too need to provide character encoding, if you lot don't then the platform'due south default character encoding is used. In Java IO, streams similar InputStream are used to read bytes, and Readers like FileReader are used to read character data.
BufferedReader is the traditional style to read data because it reads file buffer by buffer instead of character past character, so it's more efficient if you are reading large files. BufferedReader is too there from JDK i itself while Scanner was added to Java 5.
The scanner has more features than BufferedReader, when information technology comes to file reading, for instance, you can specify any delimiter instead of the new line, which is not possible with BufferedReader. Java vii added a new File API, which makes reading/writing from the file even easier.
It'southward besides possible to read the entire file in i line in Java 7, merely given about of the projects are still running on Java 6, it's practiced to know near these two means to read a text file in Java. For Java beginners, I also propose referring to a expert book like Cay S. Horstmann, Core Java Volume one and two to acquire the basics of Coffee programming.
How to read a text file in Coffee? Examples
You can read a text file in the Java program by using BufferedReader and Scanner and we will talk over steps to read a file in this article. Showtime, we will see how to employ the Scanner class to read a file line by line in Java, and then we will learn how to use BufferedReader class to do the same.
Example 1 - Reading File using Scanner in Java
Scanner form is divers in coffee.util package, so the first stride is to import this grade into your Java program. In one case you imported this class, yous can create an object of Scanner by passing a FileInputStream to it, pointing to the file you want to read.
Now you lot are all prepare to read a text file line by line in Java. The scanner provides a method called hasNextLine() which returns truthful if the file has i more line to read.
This check is platform-independent and then information technology will work in both Windows and UNIX even though the line separator is unlike in these two operating systems due east.g. line separator is \due north in Windows and \r\due north in UNIX.
You can read data from the file by calling nextLine() method, this volition return the next line and accelerate the file pointer to the next line. This method returns a Cord object representing a line in the file. You can utilize a while() loop equally shown in our kickoff case, to read all lines from files one by one.
Y'all can also run across Core Java Volume two - Advanced Features by Cay S. Horstmann to learn more nearly how to use Scanner to read a file in Java.
Instance ii - Reading Text File using BufferedReader in Java
BufferedReader provides another way to read files line past line in Coffee. Information technology follows a decorator pattern and adds buffering capability to an existing reader. Yous can create an object of InputStreamReader by passing FileInputStream, pointing to the text file you want to read.
Optionally, you can also provide graphic symbol encoding to the InputStreamReader, if you lot don't then it will use the platform's default character encoding. InputStreamReader actually acts equally a bridge between streams and reader classes.
One time you lot accept an object of BufferedReader, you tin call thereadLine() method to read the next line from the file. This method returns a Cord object containing data from a file, if there is no more line to read then this method render null. By using this properly, you tin can write a while loop to read a file line by line in Java, as shown in our second instance.
Though I have not closed the buffered reader here, you should exercise it on your real production code, equally suggested earlier on the correct fashion to close streams in Coffee. It'due south better to call theshut() method on the finally block. If you are on Java 7, consider using try-with-resource argument to automatically shut resources once you are washed with it. You tin also use the Files class to read whole file in one line.
Java Program to read a file line past line in Java
Here is our complete Java programme to read a file in Java. This programme contains two examples, the showtime example shows how to read a text file using theScanner class and the 2nd example shows how to read a file using BufferedReader class.
Both classes are divers in java.util package so yous need to import them before using them. If you are coding in Eclipse then don't worry, Eclipse will take care of it. In lodge to run this program from the command line, create a Coffee source file with the name FileReaderDemo.java and write this program there.
Once you are washed with it, y'all can follow the steps given on how to run Helloworld in Java to run this programme from the command line. If you are using Eclipse IDE, then only select a Java projection and copy-paste this code there, Eclipse will have care residuum of information technology. To run a program in Eclipse, just right-click and select "Run as Java Program".
import java.io.BufferedReader; import java.io.FileInputStream; import coffee.io.IOException; import coffee.io.InputStreamReader; import java.util.Scanner; /** * Java program to read File in Java. Information technology demonstrate ii ways past simple example, * i uses java.util.Scanner grade and other by using java.io.BufferedReader * course. * * @author http://java67.blogspot.com * */ public class FileReaderDemo{ public static void main(String args[]) throws IOException { final Cord FILE_NAME = "C://temp//Gross domestic product.txt"; // 1st style to read File in Coffee - Using Scanner Scanner scnr = new Scanner(new FileInputStream(FILE_NAME)); while (scnr.hasNextLine()) { Organisation .out.println(scnr.nextLine()); } scnr.shut(); // 2nd way to read File in Coffee - Using BufferedReader BufferedReader buffReader = new BufferedReader( new InputStreamReader(new FileInputStream(FILE_NAME))); String line = buffReader.readLine(); while (line != null) { Arrangement .out.println(line); line = buffReader.readLine(); } } }Output : United States eighteen,390.900 Communist china fifteen,923.626 India 5,750.467 Japan five,021.990 Germany 3,440.437 Russian federation two,827.978 Brazil 2,656.858 United Kingdom 2,562.320 France 2,416.128 United mexican states ii,040.222
That's all near how to read a text file in Java using BufferedReader and Scanner. Use Scanner if you are running on Coffee v or Java vi, or utilise BufferedReader if you are running on Coffee 1.4. You can utilise the Files grade to read text files from Java 7 onward.
If you like this tutorial and interested to learn more about Files and directories in Coffee, You lot can likewise take a expect at the post-obit Coffee tutorials :
- How to read XLS and XLSX files in Java using Apache POI? (example)
- How to create a file and directory in Coffee? (solution)
- How to read XML files in Coffee using JDOM Parser? (solution)
- How exercise you utilize the Scanner form in Coffee? (example)
- How to use BufferedReader class in Java? (demo)
- How do I read InputStream as String in Java? (solution)
- How to read JSON Files in Java? (solution)
- How do I read input from the console in Java? (example)
Don't forget to close the Scanner and BufferedReader object once you are done with information technology. Also, provide a character encoding if your file's encoding is unlike than the platform's grapheme encoding.
Source: https://www.java67.com/2015/06/2-ways-to-read-text-file-in-java-6.html
Post a Comment for "How to Write a Loop About Reading a File in Java"