Quantcast
Channel: How do I create a Java string from the contents of a file? - Stack Overflow
Viewing all articles
Browse latest Browse all 36

Answer by Jon Skeet for How do I create a Java string from the contents of a file?

$
0
0

That code will normalize line breaks, which may or may not be what you really want to do.

Here's an alternative which doesn't do that, and which is (IMO) simpler to understand than the NIO code (although it still uses java.nio.charset.Charset):

public static String readFile(String file, String csName)            throws IOException {    Charset cs = Charset.forName(csName);    return readFile(file, cs);}public static String readFile(String file, Charset cs)            throws IOException {    // No real need to close the BufferedReader/InputStreamReader    // as they're only wrapping the stream    FileInputStream stream = new FileInputStream(file);    try {        Reader reader = new BufferedReader(new InputStreamReader(stream, cs));        StringBuilder builder = new StringBuilder();        char[] buffer = new char[8192];        int read;        while ((read = reader.read(buffer, 0, buffer.length)) > 0) {            builder.append(buffer, 0, read);        }        return builder.toString();    } finally {        // Potential issue here: if this throws an IOException,        // it will mask any others. Normally I'd use a utility        // method which would log exceptions and swallow them        stream.close();    }        }

Viewing all articles
Browse latest Browse all 36

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>