November 16, 2020 The usage of FileReader class and BufferedReader class is summarized again.
It is an API for reading a text file, and is used to perform processing based on the contents of the text file. The characters in the file are read in a stream of characters that can read and write data character by character. The FileReader class has only a read method that reads characters one by one, so if you want to read data in a stream of bytes that can be read and written in byte units, use the FileInputStream class.
Read character by character with read method
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
//Specify the file path as an argument of the File class constructor
File file = new File("text.txt");
//Exception handling when the file does not exist
//The exists method returns true if the file exists, false if it does not exist
if (!file.exists()) {
System.out.print("File does not exist");
return;
}
//Read and display character by character using FileReader class and read method
FileReader fileReader = new FileReader(file);
int data;
//Repeat until the end of the file
while ((data = fileReader.read()) != -1) {
//Cast the read character to char type and display the character
System.out.print((char) data);
}
//Finally close the file to free resources
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Like the FileReader class, it is a class that reads text files, and the methods provided are different from the FileReader class. The BufferReader class provides a readline method that reads line by line. The FileReader class reads one character at a time, but if the number of characters is large, it may become inefficient, so decide a certain amount of memory and issue a read command to the OS when it accumulates. This is called buffering.
Read line by line with the readline method
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
//Specify the file path as an argument of the File class constructor
File file = new File("c:SampleTest.txt");
//Exception handling when the file does not exist
//The exists method returns true if the file exists, false if it does not exist
if (!file.exists()) {
System.out.print("File does not exist");
return;
}
//Read and display line by line using the readLine method of the BufferedReader class
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String data;
//Repeat until the end of the file
while ((data = bufferedReader.readLine()) != null) {
System.out.println(data);
}
//Finally close the file to free resources
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Class BufferedReader Class FileReader [Java] Read text files with FileReader and BufferedReader
Recommended Posts