java读取txt文件内容
时间: 2023-06-24 12:08:58 浏览: 52
你可以使用 Java 中的 File 和 Scanner 类来读取文本文件的内容。以下是一个简单的示例:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileExample {
public static void main(String[] args) {
try {
// 创建一个文件对象
File file = new File("example.txt");
// 创建一个Scanner对象来读取文件内容
Scanner scanner = new Scanner(file);
// 读取文件内容
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
// 关闭Scanner对象
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("文件未找到:" + e.getMessage());
}
}
}
```
在上面的示例中,我们首先创建一个 File 对象来表示要读取的文本文件。然后我们使用 Scanner 对象来读取文件内容。在 while 循环中,我们使用 `hasNextLine()` 方法检查是否还有下一行,如果有,我们就使用 `nextLine()` 方法读取下一行内容并打印出来。最后,我们关闭 Scanner 对象以释放资源。
请注意,这个示例假设 example.txt 文件已经存在,并且在与 Java 文件相同的目录下。如果要读取其他目录中的文件,需要提供完整的文件路径。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![none](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)