Javascript required
Skip to content Skip to sidebar Skip to footer

Java Read in Text File From Command Line

Every bit I told you before that in that location are multiple means to read a file in Java e.1000. FileReader, BufferedReader, and FileInputStream. You chose the Reader or InputStream depending upon whether you are reading text information or binary data, for example, the BufferedReader class is mostly used to read a text file in Java. The Scanner course is also another manner to read a text file in java. Even though Scanner is more popular as a utility to read user input from the command prompt, y'all will be glad to know that you tin can also read a file using Scanner.

Similar to BufferedReader, information technology provides buffering merely with a smaller buffer size of 1KB and you can also use the Scanner to read a file line by line in Java.

Similar to readLine() , the Scanner class as well have nextLine() method which return the next line of the file. Scanner also provides parsing functionality e.g. y'all can non but read text but parse it into correct data blazon e.g. nextInt() can read integer andnextFloat() can read float and so on.

The java.util.Scanner is as well a newer class compared to BufferedReader, just added on Coffee one.five version, so you lot tin can't guarantee its availability on all Java versions, but to be honest in 2016 with Coffee 8 already over 2 years one-time, Java 5 is the end of life. And then, for most of the applied purposes, Scanner should exist taken equally granted.

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

Y'all can as well meet Core Java Volume II - Advanced Features by Cay S. Horstmann to learn more nearly how Scanner parses the text data while reading.  Anyway, let' see the Scanner instance to read a text file to understand more.

How to read text file line past line using Scanner

Here is a sample code 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(Cord          file) {     try {       Scanner sc          =          new          Scanner(new          File(file));          while          (sc.hasNext()) {          Cord          str          =          sc.nextLine();         System.out.println(str);       }       sc.close();     } catch (IOException due east) {          // TODO Car-generated grab cake          e.printStackTrace();     }   }

You can see that we accept used hasNext() method to check if there are more lines left and and so used nextLine() to actually read the line. Don't forget to close the Scanner one time yous are washed to foreclose resource leak. This is i of the recommended coding guidelines for Coffee programmers to write robust programs, you can as well encounter Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs for more best practices.

How to read a text file using Scanner in Java?

Btw, yous can even apply next() to read text file word by word as shown in the case in next section.

Java Program to read a text file using Scanner

Here is our complete Java programme which demonstrates usage of both nextLine() and adjacent() methods to read data from a text file in Java. By default, thenext() method read file discussion by give-and-take, where words are separated past whitespace. In this example, nosotros volition read a text file chosen "file1.txt", which contains the following lines:

file1.txt
Coffee, JavaScript, Jython

You lot can come across the file simply contains 1 line just iii words which are separated by infinite. Btw, reading from a file using Scanner is no different than reading an input stream from the keyboard, which is the most popular usage of Scanner course in Java. Merely thing changes are the source, in the instance of a file, the source is the file itself.

reading text file in Java using Scanner

Reading a text file using Scanner in 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          coffee.util.List;          import          java.util.Scanner;          /*  * Java Program read a text file in multiple style.  * This plan demonstrate how yous can employ FileReader,  * BufferedReader, and Scanner to read text file,  * forth with newer utility methods added in JDK vii  * and 8.   */          public          class          ScannerExample          {          public          static          void          main(Cord[] args) throws Exception {          // reading a text file line by line using Scanner          Organization.out.println("Reading a text file line by line: ");     Scanner sc          =          new          Scanner(new          File("file.txt"));          while          (sc.hasNext()) {          String          str          =          sc.nextLine();          Organization.out.println(str);     }     sc.close();          // reading all words from file using Scanner          System.out.println("Reading a text file word by word: ");     Scanner sc2          =          new          Scanner(new          File("file.txt"));          while          (sc2.hasNext()) {          Cord          give-and-take          =          sc2.next();          Organisation.out.println(word);     }      sc2.close();    } }   Output Reading a          text          file line by line:          Java, JavaScript, Jython Reading a          text          file discussion by discussion:          Java, JavaScript, Jython

That's all about how to read a text file using Scanner in Coffee. The java.util.Scanner is a nice and powerful grade to non simply allow you to read user input but allows you to read a text file as well. You can also customize the beliefs of thenext() method by using nextPattern() method which reads the next matching design specified by the regular expression you give to the Scanner class.

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

Other Java File tutorials you may discover interesting:

  • Useful differences between BufferedReader and Scanner in Java? (answer)
  • How to read an XML file in Java? (guide)
  • How to read a ZIP 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 Cord in Java? (example)
  • How to copy non-empty directories in Java? (example)
  • 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 Java? (example)
  • iii ways to read a file line by line in Java 8? (tutorial)
  • How to read a file in ane line in Java viii? (solution)
  • How to read and write a text file in Java? (example)

In the end, using the correct tool for the job matters, so utilise BufferedReader if you just take to read a text file and utilise Scanner if you also need to parse the data. Also, remember that the buffer size in Scanner is much smaller than Scanner due east.grand. 1KB compared to 8KB of BufferedReader.


mcwilliambeerbeen.blogspot.com

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