Java readFile

From EggeWiki
Revision as of 22:43, 25 August 2009 by Brianegge (talk | contribs) (Created page with '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…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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>