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

$
0
0

If you're looking for an alternative that doesn't involve a third-party library (e.g. Commons I/O), you can use the Scanner class:

private String readFile(String pathname) throws IOException {    File file = new File(pathname);    StringBuilder fileContents = new StringBuilder((int)file.length());            try (Scanner scanner = new Scanner(file)) {        while(scanner.hasNextLine()) {            fileContents.append(scanner.nextLine() + System.lineSeparator());        }        return fileContents.toString();    }}

Viewing all articles
Browse latest Browse all 36

Trending Articles



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