Here you can find the source of readFile(File path)
Parameter | Description |
---|---|
path | path of the file to read |
Parameter | Description |
---|---|
IOException | on any error |
public static String readFile(File path) throws IOException
//package com.java2s; //License from project: Apache License import java.io.*; public class Main { private static final int BUFFER_SIZE = 8192; /**/*from w w w . j av a 2s .c o m*/ * Reads the entire contents of the file at the given path and returns it as a String. Uses the default locale. * * @param path path of the file to read * @return the file content as a String * @throws IOException on any error */ public static String readFile(File path) throws IOException { InputStreamReader reader = null; try { StringWriter writer = new StringWriter(); reader = new InputStreamReader(new FileInputStream(path)); int n; char[] buffer = new char[BUFFER_SIZE]; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } reader.close(); return writer.toString(); } finally { failsafeClose(reader); } } /** * Closes a given closeable if it is not null, and ignores thrown errors. Useful for finally * clauses which perform last-ditch cleanup and don't want to throw (masking earlier errors). * * @param closeable to be closed */ public static void failsafeClose(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { // Ignored. } } } }