How to use Java IO API to read txt files in Java
To use the Java IO API to read txt files, the following code example can be used:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadTxtFile {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we used the 'FileReader' and 'BufferedReader' classes to read the txt file. Firstly, we create a 'FileReader' object and pass in the file path to be read. Then, we create a 'BufferedReader' object and pass the 'FileReader' object into it. Next, we use the 'readLine()' method to read the file content line by line until we reach the last line. Finally, we close the 'BufferedReader' and 'FileReader' objects.
It should be noted that the file path in the above code is a relative path, meaning that the txt file should be located in the same directory as the Java file. If the txt file is located in a different directory, an absolute path can be used to specify it.
If you want to use a third-party library to read txt files, you can use the Apache Commons IO library, which provides more convenient file manipulation methods. In the Maven project, the following dependencies can be added:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
The example code for using the Apache Commons IO library is as follows:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class ReadTxtFile {
public static void main(String[] args) {
try {
File file = new File("example.txt");
List<String> lines = FileUtils.readLines(file, "UTF-8");
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code uses the 'readLines()' method of the 'FileUtils' class to read the content of the entire txt file at once and return a list containing all lines. Then, we can traverse the list and print out the content of each row.
In order for the sample code to run successfully, it is necessary to create a txt file called "example. txt" and ensure that it is located in the same directory as the Java file. The txt file can contain any text content, such as:
Hello
World
Java
IO
API
This txt file has five lines of content, one word per line.