|
9 | 9 | import java.io.StringReader; |
10 | 10 | import java.io.Writer; |
11 | 11 | import java.nio.charset.Charset; |
| 12 | +import java.nio.charset.StandardCharsets; |
12 | 13 |
|
13 | 14 | import org.apache.commons.io.FileUtils; |
14 | 15 | import org.apache.commons.io.IOUtils; |
|
17 | 18 | import org.slf4j.Logger; |
18 | 19 | import org.slf4j.LoggerFactory; |
19 | 20 |
|
| 21 | +import com.google.common.base.Charsets; |
20 | 22 | import com.google.common.io.CharSink; |
21 | 23 | import com.google.common.io.CharSource; |
22 | 24 | import com.google.common.io.CharStreams; |
@@ -179,7 +181,45 @@ public void givenUsingGuava_whenConvertingReaderIntoInputStream_thenCorrect() th |
179 | 181 | public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException { |
180 | 182 | final Reader initialReader = new StringReader("With Commons IO"); |
181 | 183 |
|
182 | | - final InputStream targetStream = IOUtils.toInputStream(initialReader.toString()); |
| 184 | + final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader)); |
| 185 | + |
| 186 | + initialReader.close(); |
| 187 | + targetStream.close(); |
| 188 | + } |
| 189 | + |
| 190 | + // tests - Reader to InputStream with encoding |
| 191 | + |
| 192 | + @Test |
| 193 | + public void givenUsingPlainJava_whenConvertingReaderIntoInputStreamWithCharset_thenCorrect() throws IOException { |
| 194 | + final Reader initialReader = new StringReader("With Java"); |
| 195 | + |
| 196 | + final char[] charBuffer = new char[8 * 1024]; |
| 197 | + final StringBuilder builder = new StringBuilder(); |
| 198 | + int numCharsRead; |
| 199 | + while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) { |
| 200 | + builder.append(charBuffer, 0, numCharsRead); |
| 201 | + } |
| 202 | + final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes(StandardCharsets.UTF_8)); |
| 203 | + |
| 204 | + initialReader.close(); |
| 205 | + targetStream.close(); |
| 206 | + } |
| 207 | + |
| 208 | + @Test |
| 209 | + public void givenUsingGuava_whenConvertingReaderIntoInputStreamWithCharset_thenCorrect() throws IOException { |
| 210 | + final Reader initialReader = new StringReader("With Guava"); |
| 211 | + |
| 212 | + final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes(Charsets.UTF_8)); |
| 213 | + |
| 214 | + initialReader.close(); |
| 215 | + targetStream.close(); |
| 216 | + } |
| 217 | + |
| 218 | + @Test |
| 219 | + public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException { |
| 220 | + final Reader initialReader = new StringReader("With Commons IO"); |
| 221 | + |
| 222 | + final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8); |
183 | 223 |
|
184 | 224 | initialReader.close(); |
185 | 225 | targetStream.close(); |
|
0 commit comments