Is there a way to close Writer without closing the main thread?

I have a socket in which I write some character data, and some raw byte data. For character data, it's easier to use PrintWriter. For raw byte data, it is easier to write directly to OutputStream. Therefore, in all my code, I have these segments:

Writer writer = new PrintWriter(outputStream);
writer.write(someText);
...
writer.flush();
// No call to writer.close(), because that would close the underlying stream.

While I try not to write to this one Writerafter I start writing to the stream in some other way, this is normal. But I would prefer that I know what I get IOExceptionif I accidentally write to a stream (as if I had closed it).

Is there a way to explicitly prohibit future recording in Writerwithout closing its underlying stream?

+5
source share
5 answers

, . Java io, . , , , .

+7

? close() : (1) (2) close() . (2), flush() close() .

+9

, , , :

class CombinedWriter extends Writer {
    private boolean isWritingBinary;
    private Writer mWriter;
    private OutputStream mOutputStream;
    public void write(byte[] bytes) {
        // flush the writer if necessary
        isWritingBinary = true;
        mOutputStream.write(bytes);
    }
    public void write(String string) {
        // flush if necessary
        isWritingBinary = false;
        mWriter.write(string);
    }
    public void flush() {
        // ...
    }
    public void close() {
        // ...
    }
}

Writer; , .

- , ; , - , (, Android-).

0

OutputStream :

byte strBin[] = someText.getBytes("UTF-8");
outputStream.write(strBin);

"UTF-8", .

0

! , . , , , , , .

HTTP- jpg, . - OutputStream Java Socket.

PrintWriter , . , , , .

Printwriter Printwriter , . PrintWriter , ( , ). , .

In the end, you can simply close PrintWriterto close the underlying thread.

If you use the class below, you should:

  1. HttpStreamWriterImplby providing OutputStreamfor the base Socket.
  2. If necessary writeLine().
  3. Call writeBinary()if / if necessary.
  4. By close()click " close().

Example:

public class HttpStreamWriterImpl implements Closeable
{
    private @NotNull OutputStream stream;
    private @NotNull PrintWriter printWriter;

    public HttpStreamWriterImpl(@NotNull OutputStream stream)
    {
        this.stream = stream;
        this.printWriter = new PrintWriter(stream, true, UTF_8);
    }

    public void writeLine(@NotNull String line)
    {
        printWriter.print(line);
        printWriter.print(HTTP_LINE_ENDING);
    }

    public void writeBinary(@NotNull byte[] binaryContent) throws IOException
    {
        printWriter.flush();
        stream.write(binaryContent);
        stream.flush();
    }

    @Override
    public void close()
    {
        printWriter.close();
    }
}
0
source

All Articles