How To Read A Text File Using Scanner Inwards Java? Illustration Tutorial

As I told you lot earlier that at that spot are multiple ways to read a file inwards Java e.g. FileReader, BufferedReader, together with FileInputStream. You chose the Reader or InputStream depending upon whether you lot are reading text information or binary data, for example, the BufferedReader flat is generally used to read a text file inwards Java. The Scanner flat is also only about other agency to read a text file inwards java. Even though Scanner is to a greater extent than pop equally a utility to read user input from the ascendence prompt, you lot volition hold upward glad to know that you lot tin also read a file using Scanner. Similar to BufferedReader, it provides buffering but amongst a smaller buffer size of 1KB together with you lot tin also job the Scanner to read a file trouble past times line inwards Java. Similar to readLine(), Scanner flat also receive got nextLine() method which render the side past times side trouble of the file. Scanner also provides parsing functionality e.g. you lot tin non alone read text but parse it into right information type e.g. nextInt() tin read integer and nextFloat() tin read float together with thence on.

The java.util.Scanner is also a newer flat compared to BufferedReader, alone added on Java 1.5 version, thence you lot can't guarantee its availability on all Java version, but to hold upward honest inwards 2016 amongst Java 8 already over two years old, Java five is the halt of life. So, for most of the practical purpose, Scanner should hold upward taken equally granted.

In this article, I'll portion a couplet of examples of reading a text file using Scanner. It provides an array of next() methods e.g. next(), nextLine(), nextInt(), or nextFloat(). The next() method render the side past times side token where the delimiter is past times default space, acre nextLine() render side past times side trouble where trouble terminator tin hold upward \n or \r\n .

You tin also see Core Java Volume II - Advanced Features past times Cay S. Horstmann to larn to a greater extent than almost how Scanner parse the text information acre reading.  Anyway, let' run across the Scanner illustration to read a text file to sympathise more.





How to read text file trouble past times trouble using Scanner

Here is sample code illustration of how you lot tin read a text file trouble past times trouble using Scanner. It uses nextLine() to read a file trouble past times line.

public static void readTextFileUsingScanner(String file) {     receive {       Scanner sc = new Scanner(new File(file));       while (sc.hasNext()) {         String str = sc.nextLine();         System.out.println(str);       }       sc.close();     } grab (IOException e) {       // TODO Auto-generated grab block       e.printStackTrace();     }   }

You tin run across that nosotros receive got used hasNext() method to banking concern check if at that spot are to a greater extent than lines left together with and then used nextLine() to genuinely read the line. Don't forget to unopen the Scanner in ane lawsuit you lot are done to preclude resources leak. This is ane of the recommended coding guidelines for Java programmers to write robust programs, you lot tin also see Java Coding Guidelines: 75 Recommendations for Reliable together with Secure Programs for to a greater extent than best practices.

 As I told you lot earlier that at that spot are multiple ways to read a file inwards Java e How to read a text file using Scanner inwards Java? Example Tutorial


Btw, you lot tin fifty-fifty job next() to read text file give-and-take past times give-and-take equally shown inwards the illustration inwards side past times side section.



Java Program to read a text file using Scanner

Here is our consummate Java plan which demonstrates usage of both nextLine() together with next() method to read information from a text file inwards Java. By default, next() method read file give-and-take past times word, where words are separated past times whitespace. In this example, nosotros volition read a text file called "file1.txt", which contains next lines:

file1.txt
Java, JavaScript, Jython

You tin run across the file alone contains ane trouble but 3 words which are separated past times space. Btw, reading from a file using Scanner is no dissimilar than reading an input current from the keyboard, which is the most pop usage of Scanner flat inwards Java. Only thing changes are the source, inwards the instance of a file, the beginning is the file itself.

 As I told you lot earlier that at that spot are multiple ways to read a file inwards Java e How to read a text file using Scanner inwards Java? Example Tutorial



Reading a text file using Scanner inwards Java
import java.io.BufferedReader; import java.io.File; import java.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 inwards multiple way.  * This plan demonstrate how you lot tin job FileReader,  * BufferedReader, together with Scanner to read text file,  * along amongst newer utility methods added inwards JDK vii  * together with 8.   */ public class ScannerExample {    public static void main(String[] args) throws Exception {      // reading a text file trouble past times trouble using Scanner     System.out.println("Reading a text file trouble past times line: ");     Scanner sc = new Scanner(new File("file.txt"));     while (sc.hasNext()) {       String str = sc.nextLine();       System.out.println(str);     }     sc.close();       // reading all words from file using Scanner     System.out.println("Reading a text file give-and-take past times word: ");     Scanner sc2 = new Scanner(new File("file.txt"));     while (sc2.hasNext()) {       String give-and-take = sc2.next();       System.out.println(word);     }      sc2.close();    } }   Output Reading a text file trouble past times line:  Java, JavaScript, Jython Reading a text file give-and-take past times word:  Java, JavaScript, Jython


That's all almost how to read a text file using Scanner inwards Java. The java.util.Scanner is a prissy together with powerful flat to non alone allow you lot to read user input but allows you lot to read a text file equally well. You tin also customize the behaviour of next() method past times using nextPattern() method which read side past times side matching designing specified past times the regular appear you lot orbit to Scanner class.

You tin farther read Big Java: Early objects to know to a greater extent than almost capabilities of Scanner flat together with how you lot tin receive got total payoff of this prissy utility for reading user input, files, together with from other sources.

Other Java File tutorials you lot may detect interesting:
  • Useful differences betwixt BufferedReader together with Scanner inwards Java? (answer)
  • How to read an XML file inwards Java? (guide)
  • How to read a ZIP file inwards Java? (tutorial)
  • How to append text to a File inwards Java? (solution)
  • How to read the XLS together with XLSX files inwards Java? (guide)
  • How to read an XML file equally String inwards Java? (example)
  • How to re-create non-empty directory inwards Java? (example)
  • How to read/write from/to RandomAccessFile inwards Java? (tutorial)
  • How to banking concern check if a File is hidden inwards Java? (solution)
  • How to read from a Memory Mapped file inwards Java? (example)
  • 3 ways to read a file trouble past times trouble inwards Java 8? (tutorial)
  • How to read a file inwards ane trouble inwards Java 8? (solution)
  • How to read together with write a text file inwards Java? (example)
In the end, using the right tool for the project matters, thence job BufferedReader if you lot only receive got to read a text file together with job Scanner if you lot also demand to parse the data. Also, scream upward that buffer size inwards Scanner is much smaller than Scanner e.g. 1KB compared to 8KB of BufferedReader.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

0 Response to "How To Read A Text File Using Scanner Inwards Java? Illustration Tutorial"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel