How to Read a Text File Line by Line in Java Scanner

As I told you earlier that at that place are multiple ways to read a file in Java east.g. FileReader, BufferedReader, and FileInputStream. You lot chose the Reader or InputStream depending upon whether yous are reading text data or binary information, for example, the BufferedReader course is generally used to read a text file in Java. The Scanner class is likewise another way to read a text file in java. Even though Scanner is more than popular as a utility to read user input from the command prompt, you will exist glad to know that you can too read a file using Scanner.

Similar to BufferedReader, it provides buffering but with a smaller buffer size of 1KB and you lot can also apply the Scanner to read a file line by line in Java.

Like to readLine() , the Scanner course besides have nextLine() method which return the next line of the file. Scanner also provides parsing functionality eastward.g. y'all tin can not only read text merely parse it into right data blazon e.g. nextInt() tin read integer andnextFloat() can read float so on.

The java.util.Scanner is too a newer course compared to BufferedReader, but added on Java 1.5 version, so you tin can't guarantee its availability on all Coffee versions, just to be honest in 2016 with Java 8 already over 2 years old, Java 5 is the end of life. And then, for most of the practical purposes, Scanner should be taken as granted.

In this article, I'll share a couple of examples of reading a text file using Scanner. Information technology provides an array of next() methods e.grand. next(), nextLine(), nextInt(), or nextFloat(). The next() method return the side by side token where the delimiter is by default infinite, while nextLine() render adjacent line where line terminator can be \due north or \r\due north .

You can besides see Core Java Volume II - Avant-garde Features by Cay Due south. Horstmann to larn more near how Scanner parses the text data while reading.  Anyway, allow' see the Scanner example to read a text file to sympathize more than.

How to read text file line by line using Scanner

Here is a sample lawmaking example of how you can read a text file line by line using Scanner. It uses nextLine() to read a file line by line.

          public          static          void readTextFileUsingScanner(String          file) {     try {       Scanner sc          =          new          Scanner(new          File(file));          while          (sc.hasNext()) {          String          str          =          sc.nextLine();         System.out.println(str);       }       sc.shut();     } take hold of (IOException e) {          // TODO Auto-generated catch cake          eastward.printStackTrace();     }   }

You can see that nosotros have used hasNext() method to check if in that location are more lines left and then used nextLine() to actually read the line. Don't forget to close the Scanner one time you are washed to prevent resource leak. This is one of the recommended coding guidelines for Java programmers to write robust programs, yous can also see Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs for more all-time practices.

How to read a text file using Scanner in Java?

Btw, y'all can fifty-fifty apply next() to read text file word by discussion as shown in the example in next department.

Java Program to read a text file using Scanner

Hither is our complete Java programme which demonstrates usage of both nextLine() and side by side() methods to read data from a text file in Coffee. Past default, thenext() method read file word by word, where words are separated by whitespace. In this example, we volition read a text file chosen "file1.txt", which contains the following lines:

file1.txt
Java, JavaScript, Jython

You can see the file only contains one line but 3 words which are separated by space. Btw, reading from a file using Scanner is no different than reading an input stream from the keyboard, which is the about popular usage of Scanner class in Java. Only affair changes are the source, in the case of a file, the source is the file itself.

reading text file in Java using Scanner

Reading a text file using Scanner in Coffee

          import          java.io.BufferedReader;          import          coffee.io.File;          import          coffee.io.FileReader;          import          java.io.IOException;          import          java.nio.charset.StandardCharsets;          import          java.nio.file.Files;          import          java.nio.file.Paths;          import          java.util.Collections;          import          java.util.List;          import          java.util.Scanner;          /*  * Java Program read a text file in multiple way.  * This plan demonstrate how you can employ FileReader,  * BufferedReader, and Scanner to read text file,  * along with newer utility methods added in JDK vii  * and viii.   */          public          grade          ScannerExample          {          public          static          void          main(Cord[] args) throws Exception {          // reading a text file line by line using Scanner          Organisation.out.println("Reading a text file line by line: ");     Scanner sc          =          new          Scanner(new          File("file.txt"));          while          (sc.hasNext()) {          Cord          str          =          sc.nextLine();          System.out.println(str);     }     sc.close();          // reading all words from file using Scanner          System.out.println("Reading a text file word by discussion: ");     Scanner sc2          =          new          Scanner(new          File("file.txt"));          while          (sc2.hasNext()) {          String          word          =          sc2.next();          System.out.println(give-and-take);     }      sc2.shut();    } }   Output Reading a          text          file line by line:          Java, JavaScript, Jython Reading a          text          file word by word:          Java, JavaScript, Jython

That's all well-nigh how to read a text file using Scanner in Java. The coffee.util.Scanner is a nice and powerful grade to not only let you to read user input just allows you to read a text file every bit well. You can as well customize the behavior of thenext() method by using nextPattern() method which reads the next matching design specified by the regular expression you give to the Scanner grade.

Yous tin can further read Big Java: Early objects to know more about the capabilities of the Scanner class and how you tin take full advantage of this nice utility for reading user input, files, and from other sources.

Other Java File tutorials you may detect interesting:

  • Useful differences betwixt BufferedReader and Scanner in Java? (answer)
  • How to read an XML file in Java? (guide)
  • How to read a Aught file in Java? (tutorial)
  • How to append text to a File in Coffee? (solution)
  • How to read the XLS and XLSX files in Java? (guide)
  • How to read an XML file as String in Coffee? (example)
  • How to re-create non-empty directories in Java? (instance)
  • How to read/write from/to RandomAccessFile in Java? (tutorial)
  • How to check if a File is hidden in Java? (solution)
  • How to read from a Memory Mapped file in Coffee? (case)
  • 3 means to read a file line by line in Java eight? (tutorial)
  • How to read a file in one line in Java eight? (solution)
  • How to read and write a text file in Java? (example)

In the terminate, using the right tool for the task matters, then use BufferedReader if you just have to read a text file and use Scanner if you also demand to parse the information. Also, think that the buffer size in Scanner is much smaller than Scanner e.g. 1KB compared to 8KB of BufferedReader.


romerostrapead1988.blogspot.com

Source: https://javarevisited.blogspot.com/2016/07/how-to-read-text-file-using-scanner-in-java-example-tutorial.html

0 Response to "How to Read a Text File Line by Line in Java Scanner"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel