'get byte array from very large StringBuilder

I d like to get byte from very large string. A string containing around a million of lines. Each line has 1400 characters.

The large String is successfuly generated using stringBuilder. But when I call getByte from the large string i get the exception :

java.lang.NegativeArraySizeException: -1574300626
    at java.base/java.lang.StringCoding.encodeUTF8_UTF16(StringCoding.java:923) ~[na:na]
    at java.base/java.lang.StringCoding.encodeUTF8(StringCoding.java:898) ~[na:na]
    at java.base/java.lang.StringCoding.encode(StringCoding.java:449) ~[na:na]
    at java.base/java.lang.String.getBytes(String.java:964) ~[na:na]

The code I'm using :

byte[] getByteArray() {
        int nbLine = 1_000_000;
        StringBuilder sb = new StringBuilder();
        char[] fakeArray = new char[1400];
        Arrays.fill(fakeArray, 'A');
        String oneLine = String.valueOf(fakeArray.toString()) + "\n";
        for (int i = 0; i < nbLine; i++) {
            sb.append(oneLine);
        }
        String contentString = sb.toString();

        return contentString.getBytes();
    }

Is there a way to make getbytes working with very large string ? Is there any alternative ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source