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

$
0
0

A very lean solution based on Scanner:

Scanner scanner = new Scanner( new File("poem.txt") );String text = scanner.useDelimiter("\\A").next();scanner.close(); // Put this call in a finally block

Or, if you want to set the charset:

Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" );String text = scanner.useDelimiter("\\A").next();scanner.close(); // Put this call in a finally block

Or, with a try-with-resources block, which will call scanner.close() for you:

try (Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" )) {    String text = scanner.useDelimiter("\\A").next();}

Remember that the Scanner constructor can throw an IOException. And don't forget to import java.io and java.util.

Source: Pat Niemeyer's blog


Viewing all articles
Browse latest Browse all 36

Trending Articles



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