如何把文本导入java
将文本导入Java的方法
使用java.io包中的BufferedReader和FileReader
通过BufferedReader和FileReader可以逐行读取文本文件内容。这种方法适用于处理较大的文件,因为它逐行读取,避免内存占用过高。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadTextFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用java.nio.file包中的Files类
Files类提供了readAllLines方法,可以一次性读取文件的所有行到一个List<String>中。适用于较小的文件,因为会一次性加载所有内容到内存。
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.io.IOException;
public class ReadTextFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try {
List<String> lines = Files.readAllLines(Paths.get(filePath));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Scanner类
Scanner类提供了一种简单的方式来逐行或按分隔符读取文本文件内容。适用于需要按特定格式解析文件的情况。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadTextFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (Scanner scanner = new Scanner(new File(filePath))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
使用java.nio.file包中的Files和Paths读取为字符串
如果需要将整个文件内容读取为一个字符串,可以使用Files.readString方法(Java 11及以上版本支持)。
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class ReadTextFile {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try {
String content = Files.readString(Paths.get(filePath));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用InputStream和InputStreamReader
如果需要从非文件来源(如网络或资源文件)读取文本,可以使用InputStream和InputStreamReader。

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class ReadTextFile {
public static void main(String[] args) {
try (InputStream is = ReadTextFile.class.getResourceAsStream("/file.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
- 文件路径可以是绝对路径或相对路径。相对路径相对于项目根目录或当前工作目录。
- 使用
try-with-resources语句可以确保资源(如BufferedReader或Scanner)在使用后自动关闭。 - 处理大文件时,避免使用
readAllLines或readString方法,以免内存不足。






