Quantcast
Viewing all articles
Browse latest Browse all 36

Answer by Haakon Løtveit for How do I create a Java string from the contents of a file?

After Ctrl+F'ing after Scanner, I think that the Scanner solution should be listed too. In the easiest to read fashion it goes like this:

public String fileToString(File file, Charset charset) {  Scanner fileReader = new Scanner(file, charset);  fileReader.useDelimiter("\\Z"); // \Z means EOF.  String out = fileReader.next();  fileReader.close();  return out;}

If you use Java 7 or newer (and you really should) consider using try-with-resources to make the code easier to read. No more dot-close stuff littering everything. But that's mostly a stylistic choice methinks.

I'm posting this mostly for completionism, since if you need to do this a lot, there should be things in java.nio.file.Files that should do the job better.

My suggestion would be to use Files#readAllBytes(Path) to grab all the bytes, and feed it to new String(byte[] Charset) to get a String out of it that you can trust. Charsets will be mean to you during your lifetime, so beware of this stuff now.

Others have given code and stuff, and I don't want to steal their glory. ;)


Viewing all articles
Browse latest Browse all 36

Trending Articles



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