Skip to content

Instantly share code, notes, and snippets.

@unix-junkie
Created August 6, 2019 13:56
Show Gist options
  • Save unix-junkie/e23ecabc1f577338d55d2a5b494d7232 to your computer and use it in GitHub Desktop.
Save unix-junkie/e23ecabc1f577338d55d2a5b494d7232 to your computer and use it in GitHub Desktop.
Quick'n'dirty OutputStream implementation which flushes each N bytes. Has concurrency issues =)
package com.example;
import java.io.BufferedOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicLong;
import static java.lang.String.format;
import static java.nio.file.Files.newOutputStream;
import static java.nio.file.Files.readAllBytes;
public final class RegularlyFlushingOutputStream extends FilterOutputStream {
final int flushEachBytes;
private final AtomicLong bytesWritten = new AtomicLong();
private final AtomicLong lastFlushOffset = new AtomicLong();
private RegularlyFlushingOutputStream(final OutputStream out,
final int flushEachBytes) {
super(out);
this.flushEachBytes = flushEachBytes;
}
@Override
public void write(final int b) throws IOException {
if (bytesWritten.incrementAndGet() % flushEachBytes == 0) {
flush();
}
super.write(b);
}
@Override
public void write(final byte b[], final int off, final int len) throws IOException {
final int delta = len - off;
System.out.println(format("Writing %d byte(s)", delta));
bytesWritten.addAndGet(delta);
out.write(b, off, len);
if (delta > flushEachBytes || bytesWritten.get() - lastFlushOffset.get() > flushEachBytes) {
flush();
}
}
@Override
public void flush() throws IOException {
final long bytesWrittenSnapshot = bytesWritten.get();
if (lastFlushOffset.get() != bytesWrittenSnapshot) {
System.out.println(format("Flushing at %d byte(s)", bytesWrittenSnapshot));
lastFlushOffset.set(bytesWrittenSnapshot);
}
super.flush();
}
@Override
public void close() throws IOException {
System.out.println(format("%d total byte(s) written", bytesWritten.get()));
super.close();
}
public static void main(final String ... args) throws IOException {
final int flushEachBytes = 512;
try (final OutputStream out = new RegularlyFlushingOutputStream(new BufferedOutputStream(newOutputStream(Paths.get("/tmp/passwd"))),
flushEachBytes)) {
out.write(readAllBytes(Paths.get("/etc/passwd")));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment