java读取txt内容
时间: 2023-09-14 13:06:33 浏览: 39
你可以使用Java的File和Scanner类来读取txt文件的内容,具体步骤如下:
1. 创建File对象,指定txt文件的路径。
```java
File file = new File("文件路径");
```
2. 创建Scanner对象,将File对象作为参数传入。
```java
Scanner scanner = new Scanner(file);
```
3. 使用循环遍历Scanner对象,读取每一行的内容。
```java
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// 处理每一行的内容
}
```
完整示例代码如下:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadTxtFile {
public static void main(String[] args) {
File file = new File("文件路径");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
```
其中,需要将“文件路径”替换成你实际的txt文件路径。
相关推荐
![](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)
![none](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)