我正在尝试改进 java 中的外部排序实现。
我为临时文件打开了一堆 BufferedReader 对象。我反复从每个文件中删除第一行。这插入了 Java 堆的极限。 我想要一种更具可扩展性的方法来执行此操作,而不会因为一堆构造函数调用而降低速度。
一个解决方案是只在需要时打开文件,然后读取第一行,然后将其删除。但恐怕这会慢很多。
因此,使用 Java 库是最有效的方法。
--编辑--
对于外部排序,通常的方法是将一个大文件分成几个 block 文件。对每个 block 进行排序。然后将排序后的文件视为缓冲区,从每个文件中弹出顶部项目,其中最小的是全局最小值。然后继续直到所有项目。 http://en.wikipedia.org/wiki/External_sorting
我的临时文件(缓冲区)基本上是 BufferedReader 对象。对这些文件执行的操作与堆栈/队列操作相同(查看和弹出,无需推送)。
我正在努力使这些 peek 和 pop 操作更有效率。这是因为使用许多 BufferedReader 对象会占用太多空间。
最佳答案
我现在离开我的编译器,但我认为这会工作。 编辑:工作正常。
我敦促您对它进行分析并查看。我敢打赌,与文件 I/O 和您的比较操作相比,构造函数调用将微不足道。
public class FileStack {
private File file;
private long position = 0;
private String cache = null;
public FileStack(File file) {
this.file = file;
}
public String peek() throws IOException {
if (cache != null) {
return cache;
}
BufferedReader r = new BufferedReader(new FileReader(file));
try {
r.skip(position);
cache = r.readLine();
return cache;
} finally {
r.close();
}
}
public String pop() throws IOException {
String r = peek();
if (r != null) {
// if you have \r\n line endings, you may need +2 instead of +1
// if lines could end either way, you'll need something more complicated
position += r.length() + 1;
cache = null;
}
return r;
}
}
关于java - 删除文件第一行/顶行的最快 Java 方法(如堆栈),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2564793/