To read the contents of a TXT file using Java, please follow these steps: Import the necessary packages. Create a File object pointing to the target file. Create a BufferedReader object to read the file line by line. Read the file line by line and process the contents. Close the BufferedReader object to release resources.
How to use Java to read the contents of a TXT file
To use Java to read the contents of a TXT file, You can use the following steps:
1. Import the necessary packages
<code class="java">import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException;</code>
2. Create a File object
Use the File class Create a File object pointing to the TXT file.
<code class="java">File file = new File("path/to/file.txt");</code>
3. Create a BufferedReader object
Use the FileReader class to create a BufferedReader object to read the contents of the file line by line.
<code class="java">BufferedReader br = new BufferedReader(new FileReader(file));</code>
4. Read the file line by line
Use the readLine() method of BufferedReader to read the file line by line.
<code class="java">String line; while ((line = br.readLine()) != null) { // 处理行中的内容 }</code>
5. Close BufferedReader
After reading is completed, close the BufferedReader object to release resources.
<code class="java">br.close();</code>
Sample code:
<code class="java">import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class ReadTxtFile { public static void main(String[] args) { // 文件路径 String filePath = "path/to/file.txt"; try { // 创建 File 对象 File file = new File(filePath); // 创建 BufferedReader 对象 BufferedReader br = new BufferedReader(new FileReader(file)); // 逐行读取文件 String line; while ((line = br.readLine()) != null) { // 处理行中的内容 System.out.println(line); } // 关闭 BufferedReader br.close(); } catch (IOException e) { System.out.println("读取文件失败!"); e.printStackTrace(); } } }</code>
The above is the detailed content of How to read the contents of txt in java. For more information, please follow other related articles on the PHP Chinese website!