English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to use various classes in Java to read the content of files.
To understand this example, you should understand the followingJava programmingTopic:
import java.io.BufferedInputStream; import java.io.FileInputStream; class Main { public static void main(String[] args) { try { //Create FileInputStream FileInputStream file = new FileInputStream("input.txt"); //Create BufferedInputStream BufferedInputStream input = new BufferedInputStream(file); //Read the first byte from the file int i = input.read(); while (i != -1) { System.out.print((char) i); // Read the next byte from the file i = input.read(); } input.close(); } catch (Exception e) { e.getStackTrace(); } } }
Output Result
First Line Second Line Third Line Fourth Line Fifth Line
In the above example, we use BufferedInputStreamClass from the file namedinput.txtRead the file line by line.
NoteTo run this file, you should have a file named input.txt in the current working directory.
import java.io.FileReader; import java.io.BufferedReader; class Main { public static void main(String[] args) { //Create a character array char[] array = new char[100]; try { // Create a FileReader FileReader file = new FileReader("input.txt"); //Create BufferedReader BufferedReader input = new BufferedReader(file); //Read characters input.read(array); System.out.println("Data in the file: "); System.out.println(array); //Close the reader input.close(); } catch(Exception e) { e.getStackTrace(); } } }
Output Result
Data in the file: First Line Second Line Third Line Fourth Line Fifth Line
In the above example, we useBufferedReader classRead the file namedinput.txtof the file.
import java.io.File; import java.util.Scanner; class Main { public static void main(String[] args) { try { //Create a new file object File file = new File("input.txt"); //Create a scanner object associated with the file Scanner sc = new Scanner(file); //Read each line in the file and print it out System.out.println("Use a scanner to read the file:"); while(sc.hasNextLine()) { System.out.println(sc.nextLine()); } //Close the scanner sc.close(); } catch (Exception e) { e.getStackTrace(); } } }
Output Result
Read the file using the scanner: First Line Second Line Third Line Fourth Line Fifth Line
In the above example, we created an object of the File class named file. Then, we created a Scanner object associated with the file.
Here, we use scanner methods
hasNextLine() - Returns true if the next line exists in the file
nextLine() - Return a whole line from the file
For more information about the scanner, please visitJava Scanner.