在java中编写时限制文件大小

hac*_*ker 3 java file bufferedwriter

我需要将文件大小限制为1 GB,最好使用BufferedWriter.

是否可以使用BufferedWriter或我必须使用其他库?

喜欢

try (BufferedWriter writer = Files.newBufferedWriter(path)) {   
    //...
    writer.write(lines.stream());
} 
Run Code Online (Sandbox Code Playgroud)

And*_*eas 9

您可以随时编写自己的文件OutputStream来限制写入的字节数.

以下假设您希望在超出大小时抛出异常.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您当然现在必须手动设置Writer/ OutputStream链.

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