Read file in Java

Read file in Java

Mar 02, 2022

How to read file in Java

To read file in Java, we will use the Scanner classBufferedReader class, and the FileReader class. To understand more about each method, read the descriptions below, and let’s start with the:

Scanner class

The Scanner class is available in the java.util package and if you want to use it, you need to import it. Using the Scanner to read a file in Java is very easy, even for beginners. We can parse the file and display it in our Java program using the Scanner class and you should be aware that the Scanner class is not ideal for reading passwords because it is publicly visible. Below are the methods of the Scanner class for scanning specific words or numbers. It is also useful to read file in Java.

  • Scanner (InputStream in) – This generate a scanner object from the given input stream.

  • String nextLine() – This method reads the next line of input.

  • String next() – This method reads the next word of input.

  • int nextInt() – This method reads the input that represents an integer.

  • double nextDouble() – This method reads the input that represents a floating-point number.

  • boolean hasNext() – This method will identify if there is another word in the input.

  • boolean hasNextInt() – This method will identify if there is another character that represents an integer.

  • boolean hasNextDouble() – This method will identify if there is another character that represents an floating-point number.

BufferedReader class

One of the most easiest ways to read file in Java is to use the BufferedReader class. The BufferedReader class allows you to read characters, arrays, and lines quickly and efficiently. Wrapping a BufferedReader around any reader whose read() method operations is recommended when using the BufferedReader.

Read more read file in Java

Enjoy this post?

Buy Kensoft PH a glass of milk

More from Kensoft PH