Java readFile

From EggeWiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Reading a file into a string in Ruby is as simple as:

<geshi lang="ruby"> File.new('foo.txt').read </geshi>

Unfortunately, Java has no simple method to do the same bundled with the JDK. Here's the equivalent Java function: <geshi lang="java"> public String readFile(File file) throws IOException { BufferedReader br = new BufferedReader(new FileReader(file)); String line; StringBuilder result = new StringBuilder(); while ((line = br.readLine()) != null) { result.append(line); result.append("\n"); } br.close(); return result.toString(); } </geshi>