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 finnw for How do I create a Java string from the contents of a file?

$
0
0

Guava has a method similar to the one from Commons IOUtils that Willi aus Rohr mentioned:

import com.google.common.base.Charsets;import com.google.common.io.Files;// ...String text = Files.toString(new File(path), Charsets.UTF_8);

EDIT by PiggyPiglet
Files#toString is deprecated, and due for removal Octobor 2019. Instead useFiles.asCharSource(new File(path), StandardCharsets.UTF_8).read();

EDIT by Oscar Reyes

This is the (simplified) underlying code on the cited library:

InputStream in = new FileInputStream(file);byte[] b  = new byte[file.length()];int len = b.length;int total = 0;while (total < len) {  int result = in.read(b, total, len - total);  if (result == -1) {    break;  }  total += result;}return new String( b , Charsets.UTF_8 );

Edit (by Jonik): The above doesn't match the source code of recent Guava versions. For the current source, see the classes Files, CharStreams, ByteSource and CharSource in com.google.common.io package.


Viewing all articles
Browse latest Browse all 36

Trending Articles



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