Groovy:附加到大文件

时间:2010-11-05 04:24:54

标签: groovy

如何有效地附加到大文件。我有一个必须不断附加到文件的进程,随着文件大小的增加,性能似乎也会减慢。无论如何使用append

指定大缓冲区大小

3 个答案:

答案 0 :(得分:13)

虽然Don的方法是有效的,但一般情况下(由于语法错误,它会抛出异常,而你需要flush()一个BufferedOutputStream),我一直在计划详细说明进一步(花时间)。

用于I / O操作的Groovy does not provide特殊对象。因此,您将使用Java的FileOutputStream(用于写入字节)或FileWriter(用于写入字符串)。两者都提供了一个带boolean append参数的构造函数 对于这两者,存在缓冲的装饰器BufferedOutputStreamBufferedWriter)。在此范围内,“缓冲”意味着内容不一定立即写入底层流,因此,存在I / O优化的可能性。

唐已为BufferedOutputStream提供了一个示例,此处为BufferedWriter提供了一个示例:

File file = new File("foo")
if (file.exists()) {
    assert file.delete()
    assert file.createNewFile()
}

boolean append = true
FileWriter fileWriter = new FileWriter(file, append)
BufferedWriter buffWriter = new BufferedWriter(fileWriter)

100.times { buffWriter.write "foo" }

buffWriter.flush()
buffWriter.close()

虽然Groovy不提供自己的I / O对象,但Groovy JDK (GDK)通过添加便捷方法增强了几种Java类型。在I / O输出范围内,OutputStreamFile类型相关。

所以,最后,你可以使用“Groovy方式”:

new File("foo").newOutputStream().withWriter("UTF-8") { writer ->
    100.times { writer.write "foo" + it }
}

编辑:根据您的进一步询问:

没有GDK方法允许设置缓冲区大小。

如果重复调用,上面的“Groovy”代码将覆盖该文件。 - 相反,下面的代码会将字符串附加到现有的文件中,因此可以重复调用

new File("foo").withWriterAppend("UTF-8") { it.write("bar") }

答案 1 :(得分:0)

def file = new File('/path/to/file')

// Create an output stream that writes to the file in 'append' mode
def fileOutput = new FileOutputStream(file, true)

// Buffer the output - set bufferSize to whatever size buffer you want to use
def bufferSize = 512
def fileOutput = new BufferedOutputStream(fileOutput, bufferSize)

try {
    byte[] contentToAppend = // Get the content to write to the file
    fileOutput.write(contentToAppend)
} finally {
    fileOutput.close()
}

答案 2 :(得分:0)

在Windows上的JVM中,append标志已经无效地执行了搜索操作。

当多次打开文件时,这是更新的原子,也不是非常高效。它应该在Java VM 7中的某个地方修复:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6631352