用java代码实现读取一个文件中所以的txt文件逐行读取txt文件中的内容清除所以空格和换行,判断如果等于字符串[INTRO]时,之后的读取内容方式改为两行读取内容,内容不能为空格和换行,如果等于字符串优待政策时,就改为多行读取,结束标记为服务设施,如果等于字符串服务设施时,就改为多行读取,结束标记为[GRADE],如果等于字符串[GRADE]时,就按照逐行读取内容,最后将这些数据放入数据库中
时间: 2024-03-14 11:47:35 浏览: 20
以下是Java代码的实现:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class FileParser {
public static void main(String[] args) {
File file = new File("file.txt"); // 读取的文件名
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
String type = ""; // 当前读取的类型
String content = ""; // 当前读取的内容
String prevLine = ""; // 上一行读取的内容
while ((line = reader.readLine()) != null) {
line = line.trim(); // 去除前后空格
if (line.equals("[INTRO]")) {
type = "INTRO";
prevLine = line;
} else if (line.equals("优待政策")) {
type = "POLICY";
prevLine = line;
} else if (line.equals("服务设施")) {
type = "SERVICE";
prevLine = line;
} else if (line.equals("[GRADE]")) {
type = "GRADE";
prevLine = line;
} else {
if (type.equals("INTRO")) {
if (!line.isEmpty()) { // 判断内容不为空
if (prevLine.equals("[INTRO]")) { // 按两行读取
content = line;
prevLine = line;
} else {
content += line;
prevLine = line;
}
}
} else if (type.equals("POLICY")) {
if (!line.isEmpty()) { // 判断内容不为空
if (prevLine.equals("优待政策")) { // 按多行读取
content = line;
prevLine = line;
} else {
content += "\n" + line;
prevLine = line;
}
}
if (line.equals("服务设施")) { // 结束标记
saveToDatabase(type, content); // 保存到数据库
type = "";
content = "";
}
} else if (type.equals("SERVICE")) {
if (!line.isEmpty()) { // 判断内容不为空
if (prevLine.equals("服务设施")) { // 按多行读取
content = line;
prevLine = line;
} else {
content += "\n" + line;
prevLine = line;
}
}
if (line.equals("[GRADE]")) { // 结束标记
saveToDatabase(type, content); // 保存到数据库
type = "";
content = "";
}
} else if (type.equals("GRADE")) {
if (!line.isEmpty()) { // 判断内容不为空
content = line;
saveToDatabase(type, content); // 直接保存到数据库
content = "";
}
}
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void saveToDatabase(String type, String content) {
// 将数据保存到数据库
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
String sql = "INSERT INTO data(type, content) VALUES (?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, type);
ps.setString(2, content);
ps.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ps != null) ps.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这段代码可以读取文件中的内容,并根据不同的类型进行不同的读取方式。读取到的内容会被保存到数据库中。需要注意的是,保存到数据库的代码中的数据库连接信息、表名、字段名等需要根据实际情况修改。