IOUtils.write() throws
OutOfMemoryError/NegativeArraySizeException while writing big strings
Reuse solution.
MODIFY
src/main/java/org/apache/commons/io/IOUtils.java
src/main/java/org/apache/commons/io/IOUtils.java
@@ -3193,7 +3193,7 @@ public static void write(final char[] data, final OutputStream output)
*/
public static void write(final char[] data, final OutputStream output, final Charset charset) throws IOException {
if (data != null) {
- output.write(new String(data).getBytes(Charsets.toCharset(charset)));
+ write(new String(data), output, charset);
}
}
@@ -3454,7 +3454,7 @@ public static void write(final StringBuffer data, final OutputStream output) //N
public static void write(final StringBuffer data, final OutputStream output, final String charsetName) //NOSONAR
throws IOException {
if (data != null) {
- output.write(data.toString().getBytes(Charsets.toCharset(charsetName)));
+ write(data.toString(), output, Charsets.toCharset(charsetName));
}
}
@@ -3568,11 +3568,12 @@ public static void writeLines(final Collection<?> lines, String lineEnding, fina
lineEnding = System.lineSeparator();
}
final Charset cs = Charsets.toCharset(charset);
+ final byte[] eolBytes = lineEnding.getBytes(cs);
for (final Object line : lines) {
if (line != null) {
- output.write(line.toString().getBytes(cs));
+ write(line.toString(), output, cs);
}
- output.write(lineEnding.getBytes(cs));
+ output.write(eolBytes);
}
}

MODIFY
src/test/java/org/apache/commons/io/IOUtilsTest.java
src/test/java/org/apache/commons/io/IOUtilsTest.java
@@ -601,7 +601,7 @@ public void testContentEqualsIgnoreEOL() throws Exception {
testSingleEOL("1235", "1234", false);
}
- public void testSingleEOL(String s1, String s2, boolean ifEquals) throws IOException {
+ public void testSingleEOL(final String s1, final String s2, final boolean ifEquals) throws IOException {
assertEquals(ifEquals, IOUtils.contentEqualsIgnoreEOL(
new CharArrayReader(s1.toCharArray()),
new CharArrayReader(s2.toCharArray())
@@ -1662,7 +1662,7 @@ public void testWriteBigString() throws IOException {
final String data;
try {
data = StringUtils.repeat("\uD83D", repeat);
- } catch (OutOfMemoryError e) {
+ } catch (final OutOfMemoryError e) {
System.err.printf("Don't fail the test if we cannot build the fixture, just log, fixture size = %,d%n.", repeat);
e.printStackTrace();
return;

[IO-764] IOUtils.write() throws
OutOfMemoryError/NegativeArraySizeException while writing big strings

Reuse solution.