![]() ![]() Optionally, you can also provide character encoding to the InputStreamReader, if you don't then it will use the platform's default character encoding. Once you imported this class, you can create an object of Scanner by passing a FileInputStream to it, pointing to the file you want to read. Scanner class is defined in java.util package, so the first step is to import this class into your Java program. First, we will see how to use the Scanner class to read a file line by line in Java, and then we will learn how to use BufferedReader class to do the same.Įxample 1 - Reading File using Scanner in Java You can read a text file in the Java program by using BufferedReader and Scanner and we will discuss steps to read a file in this article. How to read a text file in Java? Examples Horstmann, Core Java Volume 1 and 2 to learn the basics of Java programming. For Java beginners, I also suggest referring to a good book like Cay S. It's also possible to read the entire file in one line in Java 7, but given most of the projects are still running on Java 6, it's good to know about these two ways to read a text file in Java. Java 7 added a new File API, which makes reading/writing from the file even easier. The scanner has more features than BufferedReader, when it comes to file reading, for example, you can specify any delimiter instead of the new line, which is not possible with BufferedReader. BufferedReader is also there from JDK 1 itself while Scanner was added to Java 5. BufferedReader is the traditional way to read data because it reads file buffer by buffer instead of character by character, so it's more efficient if you are reading large files. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
March 2023
Categories |