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

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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 = null;
    StringBuilder  stringBuilder = new StringBuilder();
    String         ls = System.getProperty("line.separator");

    try {
        while((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
        }

        return stringBuilder.toString();
    } finally {
        reader.close();
    }
}

Answers

Read all text from a file

Here s a compact, robust idiom for Java 7, wrapped up in a utility method:

static String readFile(String path, Charset encoding) 
  throws IOException 
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

Read lines of text from a file

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29 http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29

List<String> lines = Files.readAllLines(Paths.get(path), encoding);

Memory utilization

The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.

The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn t need to contain the entire file. However, it s still not suitable for files that are very large relative to available memory.

For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, "large" depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM.

Character encoding

One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.

http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html

String content = readFile("test.txt", StandardCharsets.UTF_8);

http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html#defaultCharset%28%29 http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html#defaultCharset%28%29

String content = readFile("test.txt", Charset.defaultCharset());

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils