2 Ways to Read a Text File inwards Java 6

You tin read a text file inward Java half dozen past times using BufferedReader or Scanner class. Both classes render convenient methods to read a text file business past times business e.g. Scanner provides nextLine() method in addition to BufferedReader provides readLine() method. If y'all are reading a binary file, y'all tin purpose exercise FileInputStream. By the way, when y'all are reading text data, y'all too quest to render grapheme encoding, if y'all don't in addition to then platform's default grapheme encoding is used. In Java IO, streams similar InputStream are used to read bytes in addition to Readers similar FileReader are used to read grapheme data. BufferedReader is the traditional agency to read information because it reads file buffer past times buffer instead of grapheme past times character, thus it's to a greater extent than efficient if y'all are reading large files. BufferedReader is too in that location from JDK 1 itself acre Scanner was added to Java 5.

Scanner has to a greater extent than features than BufferedReader, when it comes to file reading, for instance y'all tin specify whatever delimiter instead of novel line, which is non possible alongside BufferedReader. Java seven added novel File API, which makes it reading/writing from file fifty-fifty to a greater extent than easier.

It's too possible to read entire file inward 1 business inward Java 7, but given most of the projects are notwithstanding running on Java 6, its proficient to know nearly these 2 ways to read a text file inward Java. For Java beginners, I too propose to refer a proficient majority similar Cay S. Horstmann, Core Java Volume 1 in addition to 2 to larn basics of Java programming.





How to read a text file inward Java?

You an read a text file inward Java plan past times using BufferedReader in addition to Scanner in addition to nosotros volition hash out steps to read a file inward this article. First nosotros volition run across how to purpose Scanner cast to read a file business past times line inward Java in addition to and then nosotros volition larn how to purpose BufferedReader class to exercise the same.


Solution 1 - Reading File using Scanner

Scanner cast is defined inward java.util package, thus get-go measurement is to import this cast inward your Java program. Once y'all imported this class, y'all tin create object of Scanner past times passing a FileInputStream to it, pointing to the file y'all desire to read. Now y'all are all educate to read a text file business past times business inward Java. Scanner provides a method called hasNextLine() which returns truthful if file has 1 to a greater extent than business to read.

This banking concern jibe is platform independent thus it volition operate inward both Windows in addition to UNIX fifty-fifty though business separator is unlike inward these 2 operating organisation e.g. business separator is \n inward Windows in addition to \r\n inward UNIX. You tin read information from file past times calling nextLine() method, this volition render the adjacent business in addition to advance the file pointer to adjacent line. This method render a String object representing a business inward file. You tin purpose a while() loop every bit shown inward our get-go example, to read all lines from file 1 past times one.

You tin too run across Core Java Volume 2 - Advanced Features past times Cay S. Horstmann to larn to a greater extent than nearly how to purpose Scanner to read a file inward Java.

 past times using BufferedReader or Scanner cast 2 Ways to Read a Text File inward Java 6


Solution 2 - Reading File using BufferedReader

BufferedReader provides closed to other agency to read file business past times business inward Java. It follows decorator blueprint in addition to adds buffering capability to an existing reader. You tin create an object of InputStreamReader past times passing FileInputStream, pointing to the text file y'all desire to read. Optionally, y'all tin too render grapheme encoding to the InputStreamReader, if y'all don't in addition to then it volition purpose platform's default grapheme encoding. InputStreamReader genuinely acts every bit a duo betwixt streams in addition to reader classes.

Once y'all direct keep an object of BufferedReader, y'all tin telephone telephone readLine() method to read the adjacent business from file. This method render a String object containing information from file, if in that location is no to a greater extent than business to read in addition to then this method render null. By using this properly, y'all tin write a acre loop to read a file business past times business inward Java, every bit shown inward our 2nd example.

Though I direct keep non closed buffered reader here, y'all should exercise it on your existent production code, every bit suggested before on correct agency to closed streams inward Java. Its meliorate to telephone telephone close() method on in conclusion block. If y'all are on Java 7, reckon using try-with-resource disputation to automatically closed resources 1 time y'all are done alongside it. You tin too use Files cast to read whole file inward 1 line.

 past times using BufferedReader or Scanner cast 2 Ways to Read a Text File inward Java 6




Java Program to read a file inward Java

Here is our consummate Java plan to read a file inward Java. This plan contains 2 examples, get-go instance shows how to read a text file using Scanner cast in addition to 2nd instance shows how to read a file using BufferedReader class. Both classes are defined inward java.util packet thus y'all quest to import them before using it. If y'all are coding inward Eclipse in addition to then don't worry, Eclipse volition direct keep assist of it. In gild to run this plan from ascendency line,  create a  Java origin file alongside mention FileReaderDemo.java in addition to write this plan there. Once y'all are done alongside it, y'all tin follow steps given on how to run Helloworld inward Java to run this plan from ascendency line. If y'all are using Eclipse IDE, in addition to then only direct a Java projection in addition to re-create glue this code there, Eclipse volition direct keep assist balance of it. To run a plan inward Eclipse, only correct click in addition to direct "Run every bit Java Program".


import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner;  /**  * Java plan to read File inward Java. It demonstrate 2 ways past times unproblematic example,  * 1 uses java.util.Scanner cast in addition to other past times using java.io.BufferedReader  * class.  *  * @author http://java67.blogspot.com  *  */  public class FileReaderDemo{      public static void main(String args[]) throws IOException {          final String FILE_NAME = "C://temp//GDP.txt";          // 1st agency to read File inward Java - Using Scanner         Scanner scnr = new Scanner(new FileInputStream(FILE_NAME));         while (scnr.hasNextLine()) {             System.out.println(scnr.nextLine());         }         scnr.close();          // 2nd agency to read File inward Java - Using BufferedReader         BufferedReader buffReader = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME)));         String business = buffReader.readLine();         while (line != null) {             System.out.println(line);             business = buffReader.readLine();         }     } }  
Output:  United States   18,390.900 China           15,923.626 India           5,750.467       Japan           5,021.990       Germany         3,440.437       Russia          2,827.978       Brazil          2,656.858       United Kingdom  2,562.320       France          2,416.128     Mexico          2,040.222 


That's all nearly how to read a text file inward Java using BufferedReader in addition to Scanner. Use Scanner if y'all are running on Java five or Java 6, or purpose BufferedReader is y'all are running on Java 1.4. You tin purpose Files cast to read text files cast Java seven onward. Don't forget to closed the Scanner in addition to BufferedReader object 1 time y'all are done alongside it. Also render a grapheme encoding if your file's encoding is unlike than platform's grapheme encoding.

If y'all similar this tutorial in addition to interested to larn to a greater extent than nearly Files in addition to directory inward Java, You tin too direct keep a await at next Java tutorials :
  • How to read XLS in addition to XLSX file inward Java using Apache POI? (example)
  • How to create a file in addition to directory inward Java? (solution)
  • How to read XML file inward Java using JDOM Parser? (solution)
  • How exercise y'all purpose Scanner cast inward Java? (example)
  • How to purpose BufferedReader cast inward Java? (demo)
  • How exercise I read InputStream every bit String inward Java? (solution)
  • How to read JSON File inward Java? (solution)
  • How exercise I read input from console inward Java? (example)


Recommended books for Java Beginners

Nothing beats learning cast a proficient book. You tin larn all of import Java concepts inward 1 place. Following are closed to of the proficient Java books I recommend to beginners for learning in addition to mastering fine art in addition to scientific discipline of Java programming :
  • Head First Java past times Kathy Sierra (check here)
  • Core Java, Volume 1 ninth Edition past times Cay S. Horstmann (check here)
  • Java: H5N1 Beginner's Guide past times Herbert Schildt (check here)

Subscribe to receive free email updates:

0 Response to "2 Ways to Read a Text File inwards Java 6"

Posting Komentar