我有一个基于 Spring 的 Java Web 应用程序。我的问题是:
我有一个 34MB 的文件,有 270 万行。行只是一个接一个的单词:
abc
abcdfg
xyz
etc
我需要以相当快的方式从此文件中选择 15 个随机的唯一行,这些行彼此不相邻。我知道要搜索这么大的文件我可以使用 Apache Lucene。你知道 Lucene 是否可以为我获取这些随机行吗?或者也许您有其他想法可以帮助我解决这个问题。
我真的很感激任何帮助
提前致谢
编辑:
或者也许只是将此文件放入数据库 [PostgreSQL] 中?
最佳答案
Lucene 不适合你。
只需生成随机数(确保它们不相邻),然后从文本文件中读取这些行。
这是执行此操作的代码:
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(
"MyFile.txt"));
try
{
final int MAX_NUM = <ENTER-YOUR-MAX-NUMBER-OF-LINES>;
Set<Integer> randomLines = new HashSet<Integer>();
Random rnd = new Random(System.currentTimeMillis());
for (int i = 0; i < 15; i++)
{
int aNum = rnd.nextInt(MAX_NUM);
// to make sure no lines next to each other...
if (!randomLines.contains(aNum) && !randomLines.contains(aNum+1) && !randomLines.contains(aNum-1))
{
randomLines.add(aNum);
}
}
List<String> result = new ArrayList<String>();
String aLine;
int lineNo = 0;
while ((aLine = reader.readLine()) != null)
{
if (randomLines.contains(lineNo))
{
result.add(aLine);
}
lineNo++;
}
System.out.println("Result: " + result);
}
finally
{
reader.close();
}
}
关于java - 使用 Lucene 从非常大的文件中获取随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13050010/