mikelittlewood
mikelittlewood

Reputation: 223

Java OutputStreamWriter and ByteArrayOutputStream

Why does the first example print the string 12345 but the second one doesn't?

    public static void main(String[] args) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        baos.write("12345".getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }

    String output = baos.toString();
    System.out.println(output);
    }

    public static void main(String[] args) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(baos);

    try {
        osw.write("12345");
    } catch (Exception e) {
        e.printStackTrace();
    }

    String output = baos.toString();
    System.out.println(output);
    }

Am I not using the OutputStreamWriter for its correct use?

Thanks

Upvotes: 3

Views: 1193

Answers (1)

Tasos P.
Tasos P.

Reputation: 4114

You need to flush the stream in the second example because OutputStreamWriter uses a buffer internally.

It is mentioned in the documentation

osw.flush();

Upvotes: 4

Related Questions