Posted as an answer to get around formatting problems in the comments.
An array of 2 ^ 30 char will be 2 ^ 31 bytes. Like one line, it's huge! The obvious question to ask is why you have the code:
PrintWriter out = new PrintWriter(outputFileName); out.println(gson.toJson(tokenCounter)); out.close();
This is easy to write as:
FileWriter out = new FileWriter(outputFileName); gson.toJson(tokenCounter, out); out.flush(); out.close();
This will not have a significant effect on memory and will be much faster.
This does not answer the question of why you get NPE in a large StringWriter, but to be honest, what you do is absurd ....
rolfl source share