Search

Friday, June 26, 2015

2 Ways to Read a Text File in Java 6

You can read a text file in Java 6 by using BufferedReader or Scanner class. Both class provides convenient methods to read a text file line by line e.g. Scanner provides nextLine() method and BufferedReader provides readLine() method. If you are reading a binary file, you can use use FileInputStream. By the way, when you are reading text data, you also need to provide character encoding, if you don't then platform's default character encoding is used. In Java IO, streams like InputStream are used to read bytes and Readers like FileReader are used to read character data. BufferedReader is the traditional way to read data because it reads file buffer by buffer instead of character by character, so its more efficient if you are reading large files. BufferedReader is also there from JDK 1 itself, while Scanner was added on Java 5. Scanner has more features than BufferedReader, when it comes to file reading, for example you can specify any delimiter instead of new line, which is not possible with BufferedReader. Java 7 added new File API, which makes it reading/writing from file even more easier. Its's possible to read entire file in one line in Java 7, but given most of the projects are still running on Java 6, its good to know about these two ways to read a text file in Java. For Java beginners, I also suggest to refer a good book like Cay S. Horstmann, Core Java Volume 1 and 2 to learn basics of Java programming.
Read more »

No comments:

Post a Comment