在 Java 中,索引文本文件通常使用 BufferedReader
和 InputStreamReader
类。BufferedReader
是一个字节流,用于从文件中读取文本行,并使用空格作为分隔符将行分解为字符数组。InputStreamReader
则是一个字符流,用于从文件中读取字节流并使用字符集将字节流转换为字符数组。
以下是一个简单的示例代码,用于从文件中索引文本:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TextIndexing {
public static void main(String[] args) {
String fileName = "example.txt";
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
System.err.format("Exception occurred trying to read '%s'.", fileName);
e.printStackTrace();
}
}
}
上述代码中,我们使用 BufferedReader
类从文件中读取文本行,并使用 readLine()
方法读取每行文本。我们将每行文本打印到控制台上。
如果您需要将文本文件索引并存储到数据库中,您可以使用以下代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class TextIndexingWithDB {
public static void main(String[] args) {
String fileName = "example.txt";
String dbUrl = "jdbc:mysql://localhost:3306/mydatabase";
String dbUser = "username";
String dbPassword = "password";
try {
Connection connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
PreparedStatement statement = connection.prepareStatement("INSERT INTO mytable (text) VALUES (?)");
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
while (line != null) {
statement.setString(1, line);
statement.addBatch();
line = reader.readLine();
}
statement.executeBatch();
connection.commit();
reader.close();
statement.close();
connection.close();
} catch (IOException e) {
System.err.format("Exception occurred trying to read '%s'.", fileName);
e.printStackTrace();
}
}
}
上述代码中,我们使用 jdbc
驱动将文本文件中的文本索引到 MySQL 数据库中。我们使用 PreparedStatement
类将每行文本插入到数据库中。
总之,索引文本文件是 Java 中非常常见的操作,您需要了解文本文件的读取和写入方式,以及如何使用 Java 中常用的类来实现这些操作。
小程序·云开发官方直播课(数据库方向)
Elastic 中国开发者大会
云+社区技术沙龙 [第30期]
Elastic 实战工作坊
Elastic 实战工作坊
Elastic 中国开发者大会
北极星训练营
Elastic Meetup
DB TALK 技术分享会
领取专属 10元无门槛券
手把手带您无忧上云