java如何獲取txt文本內(nèi)容

小億
310
2024-04-11 19:12:05

在Java中獲取txt文本內(nèi)容的常用方法有兩種:

  1. 使用Java I/O類讀取文本文件內(nèi)容:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadTxtFile {
    public static void main(String[] args) {
        String fileName = "example.txt";
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}
  1. 使用Apache Commons IO庫(kù)讀取文本文件內(nèi)容:

首先需要導(dǎo)入Apache Commons IO庫(kù)的依賴:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>

然后使用以下代碼讀取文本文件內(nèi)容:

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class ReadTxtFile {
    public static void main(String[] args) {
        String fileName = "example.txt";
        try {
            String content = FileUtils.readFileToString(new File(fileName), "UTF-8");
            System.out.println(content);
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

以上兩種方法都可以用來讀取txt文本文件的內(nèi)容,并輸出到控制臺(tái)或者進(jìn)行其他操作。需要注意的是,讀取文件時(shí)需要確保文件存在并且有讀取權(quán)限。

0