java按行读取文件
时间: 2023-08-20 18:09:14 浏览: 108
java按行读取大文件并解析入库
5星 · 资源好评率100%
可以使用Java中的BufferedReader类来逐行读取文件内容。下面是一个示例程序,演示了如何使用BufferedReader逐行读取文件内容:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileLineByLineUsingBufferedReader {
public static void main(String\[\] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("文件路径"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
另外,还可以使用Java 8中的Files类来实现按行读取文件的功能。示例如下:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class ReadFileLineByLineUsingFiles {
public static void main(String\[\] args) {
try {
List<String> lines = Files.readAllLines(Paths.get("文件路径"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上是两种常用的按行读取文件的方法。你可以根据自己的需求选择适合的方法来读取文件。
#### 引用[.reference_title]
- *1* [Java逐行读取文件](https://blog.csdn.net/qq_30436011/article/details/127488031)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [Java按行读取文件文本内容](https://blog.csdn.net/qq_36433289/article/details/127959932)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [Java 按行读取写入文件](https://blog.csdn.net/oh_coding/article/details/129174474)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文