如何从文本文件中读取数据?创建 File 对象以指定要读取的文件。创建 Scanner 对象作为读取文件的扫描仪。使用 nextLine() 或 next() 方法按行或按单词读取数据。使用 close() 方法关闭 Scanner 以释放资源。

从文本中读取数据
如何从文本文件中读取数据?
使用 Java 从文本文件中读取数据可以使用以下步骤:
-
创建
File对象:这将指定要读取的文件。 -
创建
Scanner对象:这将用作读取文件的扫描仪。 -
使用
nextLine()或next()方法:这些方法将按行或按单词读取数据。 -
使用
close()方法关闭Scanner:这将释放资源。
代码示例:
立即学习“Java免费学习笔记(深入)”;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFromFile {
public static void main(String[] args) {
try {
// 创建 File 对象
File file = new File("data.txt");
// 创建 Scanner 对象
Scanner scanner = new Scanner(file);
// 按行读取数据
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
// 按单词读取数据
while (scanner.hasNext()) {
String word = scanner.next();
System.out.println(word);
}
// 关闭 Scanner
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}其他方法:
除了使用 Scanner 之外,还可以使用以下方法从文本文件中读取数据:
-
BufferedReader:提供更高级别的缓冲,可以提高读取速度。 -
FileReader:字符流,必须手动处理缓冲。 -
NIO(非阻塞 I/O):一种高级 I/O API,提供异步读取。











