Limit file size while writing in java

后端 未结 4 730
情话喂你
情话喂你 2021-01-06 06:10

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

Is it possible using BufferedWriter or I have to use

4条回答
  •  庸人自扰
    2021-01-06 06:30

    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;
        }
    }
    

    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))) {
        //
    }
    

提交回复
热议问题