Index: src/main/java/java/io/BufferedWriter.java
===================================================================
--- src/main/java/java/io/BufferedWriter.java (revision 547334)
+++ src/main/java/java/io/BufferedWriter.java (working copy)
@@ -85,7 +85,7 @@
public void close() throws IOException {
synchronized (lock) {
if (!isClosed()) {
- flush();
+ flushInternal();
out.close();
buf = null;
out = null;
@@ -106,15 +106,22 @@
if (isClosed()) {
throw new IOException(Msg.getString("K005d")); //$NON-NLS-1$
}
- if (pos > 0) {
- out.write(buf, 0, pos);
- }
- pos = 0;
+ flushInternal();
out.flush();
}
}
/**
+ * Flushes the internal buffer.
+ */
+ private void flushInternal() throws IOException {
+ if (pos > 0) {
+ out.write(buf, 0, pos);
+ }
+ pos = 0;
+ }
+
+ /**
* Answer a boolean indicating whether or not this BufferedWriter is closed.
*
* @return true if this reader is closed, false
Index: src/test/java/tests/api/java/io/BufferedWriterTest.java
===================================================================
--- src/test/java/tests/api/java/io/BufferedWriterTest.java (revision 546816)
+++ src/test/java/tests/api/java/io/BufferedWriterTest.java (working copy)
@@ -19,6 +19,7 @@
import java.io.BufferedWriter;
import java.io.IOException;
+import java.io.Writer;
import tests.support.Support_StringWriter;
@@ -51,6 +52,33 @@
assertTrue("Used in tests", true);
}
+ private static class MockWriter extends Writer {
+ StringBuffer sb = new StringBuffer();
+ boolean flushCalled = false;
+
+ public void write(char[] buf, int off, int len) throws IOException {
+ for (int i = off; i < off + len; i++) {
+ sb.append(buf[i]);
+ }
+ }
+
+ public void close() throws IOException {
+ System.out.println("close");
+ }
+
+ public void flush() throws IOException {
+ flushCalled = true;
+ }
+
+ public String getWritten() {
+ return sb.toString();
+ }
+
+ public boolean isFlushCalled() {
+ return flushCalled;
+ }
+ }
+
/**
* @tests java.io.BufferedWriter#close()
*/
@@ -62,6 +90,22 @@
} catch (IOException e) {
}
assertTrue("Write after close", !sw.toString().equals(testString));
+
+ // Regression test for HARMONY-4178
+ try {
+ MockWriter mw = new MockWriter();
+ BufferedWriter bw = new BufferedWriter(mw);
+ bw.write('a');
+ bw.close();
+
+ // flush should not be called on underlying stream
+ assertFalse("Flush was called in the underlying stream", mw.isFlushCalled());
+
+ // on the other hand the BufferedWriter itself should flush the buffer
+ assertEquals("BufferdWriter do not flush itself before close", "a", mw.getWritten());
+ } catch (IOException ioe) {
+ fail("Exception during close test: " + ioe);
+ }
}
/**