Java readFile

From EggeWiki

Jump to: navigation, search

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

File.new('foo.txt').read

Unfortunately, Java has no simple method to do the same bundled with the JDK. Here's the equivalent Java function:

	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();
	}
Personal tools
Travelling Salesman

Get the app!