Improve usage of ByteArrayOutputStream/ByteArrayInputStream

Closes gh-24805
This commit is contained in:
Сергей Цыпанов
2020-03-28 19:24:09 +02:00
committed by Sam Brannen
parent 821984a5cf
commit e63d1cf12d
10 changed files with 47 additions and 40 deletions

View File

@@ -25,6 +25,7 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.Charset;
@@ -238,6 +239,24 @@ public abstract class StreamUtils {
return new NonClosingOutputStream(out);
}
/**
* More effective equivalent of {@code new String(baos.toByteArray(), charset)}
* As far as at invocation point {@code charset} is already available,
* no exception is expected to be thrown.
*
* @param baos {@link ByteArrayOutputStream} to be flushed into String
* @param charset applicable {@link Charset}
* @return String represenation of bytes stored in {@code baos}
*/
public static String baosToString(ByteArrayOutputStream baos, Charset charset) {
Assert.notNull(baos, "No ByteArrayOutputStream specified");
Assert.notNull(charset, "No Charset specified");
try {
return baos.toString(charset.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private static class NonClosingInputStream extends FilterInputStream {

View File

@@ -774,7 +774,7 @@ public abstract class StringUtils {
bos.write(ch);
}
}
return (changed ? new String(bos.toByteArray(), charset) : source);
return changed ? StreamUtils.baosToString(bos, charset) : source;
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,7 +55,6 @@ public class SerializationTestUtils {
oos.writeObject(o);
oos.flush();
}
baos.flush();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);