繁体   English   中英

在Java中使用BufferedWriter写入文件时监视文件大小?

[英]Monitor file size when writing file using a BufferedWriter in Java?

我正在将可能很长的项目列表写入文件。 我写的项目长度不定。 如果生成的文件大小大于10M,则应将其分解为多个文件。 为了提高性能,我目前正在使用BufferedWriter,如下所示:

final FileOutputStream fos = new FileOutputStream(file);
final OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
final BufferedWriter bw = new BufferedWriter(osr);

通过这样做虽然我不能准确地监视我正在写的文件的大小。 我可以经常冲洗或删除它,但是当然会对性能产生影响。 最好的选择是什么? 理想情况下,我想使生成的文件大小尽可能接近10M标记。

在这种情况下,请不要使用BufferedWriter而应使用简单的FileOutputStream (您已经拥有)。 编写(并检查)字符串的.getBytes("UTF-8") 不过,如果需要,您可能必须编写其他换行符,但这很简单。

这样,您可以提前知道必须写的大小。

以下示例使用Java 7的try -with-resources语句; 如果您要定位的是较早的平台,则必须手动关闭流。

final int MAX_BYTES = 1024 * 1024 * 10;
final int NEWLINE_BYTES = System.getProperty("line.separator")
                                .getBytes("UTF-8").length;
int bytesWritten = 0;
int fileIndex = 0;
while (existsMoreData()) {
    try (
         FileOutputStream fos = new FileOutputStream(
            getFileNameForIndex(fileIndex));
         OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
         BufferedWriter bw = new BufferedWriter(osr)) {

        String toWrite = getCurrentStringToWrite();
        int bytesOfString = toWrite.getBytes("UTF-8").length;
        if (bytesWritten + bytesOfString + NEWLINE_BYTES > MAX_BYTES
         || bytesWritten == 0 /* if this part > MAX_BYTES */ ) {

            // need to start a new file
            fileIndex++;
            bytesWritten = 0;
            continue; // auto-closed because of try-with-resources
        } else {
            bw.write(toWrite, 0, toWrite.length());
            bw.newLine();
            bytesWritten += bytesOfString + NEWLINE_BYTES;
            incrementDataToWrite();
        }

    } catch (IOException ie) {
        ie.printStackTrace();
    }
}

可能的实现:

String[] data = someLongString.split("\n");
int currentPart = 0;

private boolean existsMoreData() {
    return currentPart + 1 < data.length;
}

private String getCurrentStringToWrite() {
    return data[currentPart];
}

private void incrementDataToWrite() {
    currentPart++;
}

private String getFileNameForIndex(int index) {
    final String BASE_NAME = "/home/codebuddy/somefile";
    return String.format("%s_%s.txt", BASE_NAME, index);
    // equivalent to:
 // return BASE_NAME + "_" + index + ".txt";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM