How do I create a Java string from the contents of a file?

I’ve been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I’ve visited. Is there a better/different way to read a file into a string in Java? private String readFile(String file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader (file)); String line … Read more

Get an OutputStream into a String

I would use a ByteArrayOutputStream. And on finish you can call: new String( baos.toByteArray(), codepage ); or better: baos.toString( codepage ); For the String constructor, the codepage can be a String or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8. The method toString() accepts only a String as a codepage parameter (stand Java 8).