Read contents of a file using Scanner in Java
This post will discuss how to read the contents of a file using Scanner class in Java.
Scanner is a utility class in java.util package which can parse primitive types and strings using regular expressions. It can read text from any object which implements the Readable interface.
A plausible way of reading a file in Java is to construct a Scanner that produces values scanned from the specified file. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Scanner; class Main { public static void main(String[] args) { File file = new File("doc.txt"); try (Scanner sc = new Scanner(file, StandardCharsets.UTF_8)) { while (sc.hasNextLine()) { System.out.println(sc.nextLine()); } } catch (IOException e) { e.printStackTrace(); } } } |
We can also construct a Scanner that produces values scanned from the specified file. This is demonstrated below using the try-with-resources block to automatically takes care of scanner.close().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Scanner; class Main { public static void main(String[] args) { File file = new File("doc.txt"); String content = null; try { try (Scanner scanner = new Scanner(file, StandardCharsets.UTF_8)) { content = scanner.useDelimiter("\\A").next(); } } catch (IOException e) { e.printStackTrace(); } System.out.println(content); } } |
That’s all about reading the contents of a file using the Scanner class in Java.
Read More:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)