【问题标题】:How to write into a file without overriding the current content while limiting the file size in Java如何在不覆盖当前内容的情况下写入文件,同时限制 Java 中的文件大小
【发布时间】:2021-05-21 07:42:47
【问题描述】:

我使用此代码将一些文本写入文件,同时将文件大小限制为 1G

但每次输入新文本时,它都会覆盖当前文件内容。 如何禁用覆盖并仍然保持文件大小限制?

public synchronized void writeToAFile(String msg,String filePath) {
    Path path = FileSystems.getDefault().getPath(filePath);
    final long SIZE_1GB = 1073741824L;
    try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new LimitedOutputStream(Files.newOutputStream(path), SIZE_1GB), StandardCharsets.UTF_8))) {
        writer.append(msg);
    } catch (Exception e) {
        LOGGER.error("Something went wrong while writing to the  file {} ", e.getMessage());
        e.printStackTrace();
    }
}

【问题讨论】:

  • LimitedOutputStream 是从哪里导入的?
  • 导入 org.xnio.streams.LimitedOutputStream;

标签: java append overriding bufferedwriter


【解决方案1】:

您应该在定义Files.newOutputStream(path) 时创建可附加流。

所以提供StandardOpenOption.APPEND 选项将解决您的问题


// append to an existing file, fail if the file does not exist
// out = Files.newOutputStream(path, APPEND);

Files.newOutputStream(path, StandardOpenOption.APPEND)

要保持文件大小不变,您需要计算文件中还剩多少空间并相应地打开LimitedOutputStream

public synchronized void writeToAFile(String msg, String filePath) {
        Path path = FileSystems.getDefault().getPath(filePath);

        final long fileLength = path.toFile().length();
        final long SIZE_1GB = 1073741824L;

        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new LimitedOutputStream(Files.newOutputStream(path, StandardOpenOption.APPEND), SIZE_1GB - fileLength), StandardCharsets.UTF_8))) {
            writer.append(msg);
        } catch (Exception e) {
            LOGGER.error("Something went wrong while writing to the  file {} ", e.getMessage());
            e.printStackTrace();
        }
    }

【讨论】:

    猜你喜欢
    • 2014-04-21
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多