RFR: 8354724: BufferedReader readAllLines and readString methods [v5]
Chen Liang
liach at openjdk.org
Fri Apr 18 15:12:52 UTC 2025
On Fri, 18 Apr 2025 15:02:56 GMT, Glavo <duke at openjdk.org> wrote:
>> public static String readString() throws IOException {
>> char[] chars = new char[TRANSFER_BUFFER_SIZE];
>> int n;
>> int off = 0;
>> int rest = chars.length;
>> while ((n = read(chars, off, rest)) != -1) {
>> off += n;
>> if (n == rest) {
>> chars = Arrays.copyOf(chars, chars.length * 2);
>> }
>> rest = chars.length - off;
>> }
>> return new String(chars, 0, off);
>> }
>>
>> Maybe this version is better, it directly expands the capacity on char[] without using StringBuilder, has good performance, and does not need to add new methods.
>
> Maybe it can be implemented by referring to `InputStream::readNBytes(int)` (The default implementation of `InputStream::readAllBytes()` is based on it):
>
> https://github.com/openjdk/jdk/blob/22e8a97a1ce4e1c781fbc6f1e271c477fe95f069/src/java.base/share/classes/java/io/InputStream.java#L396-L458
If accumulation of array is necessary, I think the "variable sized array" in #24232 may help/
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/24728#discussion_r2050753970
More information about the core-libs-dev
mailing list