Home >Java >javaTutorial >How to read txt document using java

How to read txt document using java

下次还敢
下次还敢Original
2024-04-21 02:07:56859browse

Steps to use Java to read TXT documents: create a file object; create a file reader; create a buffered reader; read data line by line; close the reader.

How to read txt document using java

How to read TXT documents using Java

Reading TXT documents using Java is a simple process that only requires It takes a few steps to complete.

Step 1: Create a file object

First, you need to create a file object that represents the TXT document you want to read. To do this, use the File class:

<code class="java">File file = new File("path/to/file.txt");</code>

Step 2: Create a file reader

Next, you need to create a file reader for FileReader Object to read data:

<code class="java">FileReader reader = new FileReader(file);</code>

Step 3: Create a buffered reader

In order to read data more efficiently, you can create BufferedReader object wrapped around FileReader:

<code class="java">BufferedReader bufferedReader = new BufferedReader(reader);</code>

Step 4: Read the data line by line

Now, you You can use the readLine() method of BufferedReader to read the data in the file line by line:

<code class="java">String line;
while ((line = bufferedReader.readLine()) != null) {
    // 读取到的文本行存储在 line 变量中
}</code>

Step 5: Close the reader

After reading the file, be sure to close BufferedReader and FileReader to release system resources:

<code class="java">bufferedReader.close();
reader.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) {
        try {
            // 创建文件对象
            File file = new File("path/to/file.txt");

            // 创建文件读取器
            FileReader reader = new FileReader(file);

            // 创建缓冲读取器
            BufferedReader bufferedReader = new BufferedReader(reader);

            // 逐行读取数据
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 读取到的文本行存储在 line 变量中
                System.out.println(line);
            }

            // 关闭读取器
            bufferedReader.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}</code>

The above is the detailed content of How to read txt document using java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn