BAEL-6398: Java PrintStream to String (#13998)

This commit is contained in:
Azhwani 2023-05-16 08:28:25 +02:00 committed by GitHub
parent 3fce001db6
commit 389a106697
2 changed files with 100 additions and 0 deletions

View File

@ -0,0 +1,68 @@
package com.baeldung.printstreamtostring;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class PrintStreamToStringUtil {
public static String usingByteArrayOutputStreamClass(String input) throws IOException {
if (input == null) {
return null;
}
String output;
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
printStream.print(input);
output = outputStream.toString();
}
return output;
}
public static String usingApacheCommonsIO(String input) {
if (input == null) {
return null;
}
org.apache.commons.io.output.ByteArrayOutputStream outputStream = new org.apache.commons.io.output.ByteArrayOutputStream();
try (PrintStream printStream = new PrintStream(outputStream)) {
printStream.print(input);
}
return new String(outputStream.toByteArray());
}
public static String usingCustomOutputStream(String input) throws IOException {
if (input == null) {
return null;
}
String output;
try (CustomOutputStream outputStream = new CustomOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
printStream.print(input);
output = outputStream.toString();
}
return output;
}
private static class CustomOutputStream extends OutputStream {
private StringBuilder stringBuilder = new StringBuilder();
@Override
public void write(int b) throws IOException {
this.stringBuilder.append((char) b);
}
@Override
public String toString() {
return this.stringBuilder.toString();
}
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.printstreamtostring;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
public class PrintStreamToStringUtilUnitTest {
@Test
public void whenUsingByteArrayOutputStreamClass_thenConvert() throws IOException {
assertEquals("test", PrintStreamToStringUtil.usingByteArrayOutputStreamClass("test"));
assertEquals("", PrintStreamToStringUtil.usingByteArrayOutputStreamClass(""));
assertNull(PrintStreamToStringUtil.usingByteArrayOutputStreamClass(null));
}
@Test
public void whenCustomOutputStream_thenConvert() throws IOException {
assertEquals("world", PrintStreamToStringUtil.usingCustomOutputStream("world"));
assertEquals("", PrintStreamToStringUtil.usingCustomOutputStream(""));
assertNull(PrintStreamToStringUtil.usingCustomOutputStream(null));
}
@Test
public void whenUsingApacheCommonsIO_thenConvert() {
assertEquals("hello", PrintStreamToStringUtil.usingApacheCommonsIO("hello"));
assertEquals("", PrintStreamToStringUtil.usingApacheCommonsIO(""));
assertNull(PrintStreamToStringUtil.usingApacheCommonsIO(null));
}
}