diff --git a/src/main/java/org/codehaus/mojo/exec/LineRedirectOutputStream.java b/src/main/java/org/codehaus/mojo/exec/LineRedirectOutputStream.java index 60cd2fba..4e873b50 100644 --- a/src/main/java/org/codehaus/mojo/exec/LineRedirectOutputStream.java +++ b/src/main/java/org/codehaus/mojo/exec/LineRedirectOutputStream.java @@ -19,7 +19,12 @@ * under the License. */ +import java.io.ByteArrayOutputStream; import java.io.OutputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; import java.util.function.Consumer; /** @@ -32,8 +37,8 @@ */ class LineRedirectOutputStream extends OutputStream { - private StringBuilder currentLine = new StringBuilder(); private final Consumer linePrinter; + private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); public LineRedirectOutputStream(Consumer linePrinter) { this.linePrinter = linePrinter; @@ -45,18 +50,23 @@ public void write(final int b) { printAndReset(); return; } - currentLine.append((char) b); + buffer.write(b); } @Override public void flush() { - if (currentLine.length() > 0) { + if (buffer.size() > 0) { printAndReset(); } } + @Override + public void close() { + flush(); + } + private void printAndReset() { - linePrinter.accept(currentLine.toString()); - currentLine = new StringBuilder(); + linePrinter.accept(new String(buffer.toByteArray(), Charset.defaultCharset())); + buffer = new ByteArrayOutputStream(); } } diff --git a/src/test/java/org/codehaus/mojo/exec/LineRedirectOutputStreamTest.java b/src/test/java/org/codehaus/mojo/exec/LineRedirectOutputStreamTest.java new file mode 100644 index 00000000..0dbd5a24 --- /dev/null +++ b/src/test/java/org/codehaus/mojo/exec/LineRedirectOutputStreamTest.java @@ -0,0 +1,23 @@ +package org.codehaus.mojo.exec; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.nio.charset.Charset; + +public class LineRedirectOutputStreamTest { + + @Test + public void givenUtf8Output_whenRedirecting_thenShouldDecodeProperly() throws IOException { + StringBuilder sb = new StringBuilder(); + String firstLine = "Hello 😃 😄"; + String secondLine = "foo bar éà"; + + try (LineRedirectOutputStream os = new LineRedirectOutputStream(sb::append)) { + os.write(String.join("\n", firstLine, secondLine).getBytes(Charset.defaultCharset())); + } + + Assert.assertEquals(firstLine + secondLine, sb.toString()); + } +} \ No newline at end of file