用java代码实现读取一个文件中所以的txt文件逐行读取txt文件中的内容清除所以空格和换行,判断如果等于字符串[INTRO]时,之后的读取内容方式改为两行读取内容,内容不能为空格和换行,如果等于字符串优待政策时,就改为多行读取,结束标记为服务设施,如果等于字符串服务设施时,就改为多行读取,结束标记为[GRADE],如果等于字符串[GRADE]时,就按照逐行读取内容,最后将这些数据输出
时间: 2024-03-20 21:42:07 浏览: 22
以下是Java代码实现:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
public static void main(String[] args) {
File file = new File("file.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
String tag = "";
List<String> content = new ArrayList<>();
while ((line = br.readLine()) != null) {
line = line.replaceAll("\\s+","");
if (line.equals("[INTRO]")) {
tag = "intro";
} else if (line.equals("优待政策")) {
tag = "policy";
} else if (line.equals("服务设施")) {
tag = "service";
} else if (line.equals("[GRADE]")) {
tag = "grade";
} else {
switch (tag) {
case "intro":
if (content.size() == 0) {
content.add(line);
} else {
content.set(0, content.get(0) + line);
}
break;
case "policy":
case "service":
if (!line.isEmpty()) {
content.add(line);
}
break;
case "grade":
System.out.println(line);
break;
default:
break;
}
}
if (line.isEmpty() && tag.equals("service")) {
for (String str : content) {
System.out.println(str);
}
content.clear();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该代码实现了以下功能:
- 读取文件 `file.txt` 中的内容,并逐行处理;
- 清除每行字符串中的所有空格和换行符;
- 根据字符串标记识别不同的内容类型;
- 对于 `[INTRO]` 标记,将其后的两行内容合并到一起;
- 对于 `优待政策` 和 `服务设施` 标记,将其后的多行内容保存到 `content` 列表中;
- 对于 `[GRADE]` 标记,逐行输出其后的内容;
- 对于 `服务设施` 标记后的空行,输出 `content` 列表中的内容,并清空 `content` 列表。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)