在java中编写时限制文件大小 [英] Limit file size while writing in java

查看:215
本文介绍了在java中编写时限制文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将文件大小限制为1 GB,最好使用 BufferedWriter 进行书写。

I need to limit the file size to 1 GB while writing preferably using BufferedWriter.

是否有可能使用 BufferedWriter 还是我必须使用其他库?

Is it possible using BufferedWriter or I have to use other libraries ?

喜欢

try (BufferedWriter writer = Files.newBufferedWriter(path)) {   
    //...
    writer.write(lines.stream());
} 


推荐答案

你总是可以写自己的 OutputStream 以限制写入的字节的数量。

You can always write your own OutputStream to limit the number of bytes written.

以下假设你想要如果超出大小则抛出异常。

The following assumes you want to throw exception if size is exceeded.

public final class LimitedOutputStream extends FilterOutputStream {
    private final long maxBytes;
    private long       bytesWritten;
    public LimitedOutputStream(OutputStream out, long maxBytes) {
        super(out);
        this.maxBytes = maxBytes;
    }
    @Override
    public void write(int b) throws IOException {
        ensureCapacity(1);
        super.write(b);
    }
    @Override
    public void write(byte[] b) throws IOException {
        ensureCapacity(b.length);
        super.write(b);
    }
    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        ensureCapacity(len);
        super.write(b, off, len);
    }
    private void ensureCapacity(int len) throws IOException {
        long newBytesWritten = this.bytesWritten + len;
        if (newBytesWritten > this.maxBytes)
            throw new IOException("File size exceeded: " + newBytesWritten + " > " + this.maxBytes);
        this.bytesWritten = newBytesWritten;
    }
}

您现在必须设置 Writer / OutputStream 手动链。

You will of course now have to set up the Writer/OutputStream chain manually.

final long SIZE_1GB = 1073741824L;
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
        new LimitedOutputStream(Files.newOutputStream(path), SIZE_1GB),
        StandardCharsets.UTF_8))) {
    //
}

这篇关于在java中编写时限制文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆