Search code examples
javaiocodenameoneflush

Keeping output stream open


I wonder how to deal with OutputStreams in codenameone, which have to be kept open for a long time. There are many places, where they get written and it's be neither efficient nor error-proof to try to flush the stream everywhere. So I wrote this:

private boolean needsFlush;

private void write(byte[] data) throws IOException {
    assert Display.getInstance().isEdt();
    out.write(data);
    if (!needsFlush) {
        needsFlush = true;
        Display.getInstance().callSerially(this::flush);
    }
}

private void flush() {
    try {
        out.flush();
        needsFlush = false;
    } catch (final IOException e) {
        throw new RuntimeException(e); // UGLY!
    }
}

which should ensure that after every write, there'll be a flush sometime. Unless the app gets closed or alike.... that's why I need to ask.

  • Is it OK? Is there's better way of handling stream flushing?
  • Do they closed then properly, when the app gets terminated?
  • Do I have to add stream closing code to stop() of the "main" class?
  • Or only to destroy()?
  • What about the ugly try-catch?

Solution

  • I would suggest closing the output stream on stop() and re-opening it on start(). Notice that if the stream points to FileSystemStorage you can append to the end of the stream using CN's: OutputStream os = openFileOutputStream(filePath, lengthOfFile);.

    You need to close on stop() as the app is sent to the background. In that state you should avoid open connections as they might be terminated suddenly by the OS. The entire app can be killed because of a wayward stream.

    If you have background support in the app you should open and close the stream every time you need it.