Here you can find the source of getFileContents(File file, String charset)
Parameter | Description |
---|---|
file | the file to read |
charset | the character encoding of the file |
Parameter | Description |
---|---|
IOException | if there's a problem reading the file |
public static String getFileContents(File file, String charset) throws IOException
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; public class Main { /**/* w w w . j a v a2 s . c o m*/ * Reads the contents of a text file. * @param file the file to read * @return the file contents * @throws IOException if there's a problem reading the file */ public static String getFileContents(File file) throws IOException { return getFileContents(file, Charset.defaultCharset().name()); } /** * Reads the contents of a text file. * @param file the file to read * @param charset the character encoding of the file * @return the file contents * @throws IOException if there's a problem reading the file */ public static String getFileContents(File file, String charset) throws IOException { byte[] bytes = toByteArray(new FileInputStream(file), true); return new String(bytes, charset); } /** * Reads all the bytes from an input stream. * @param in the input stream * @return the bytes * @throws IOException if there's a problem reading from the input stream */ public static byte[] toByteArray(InputStream in) throws IOException { return toByteArray(in, false); } /** * Reads all the bytes from an input stream. * @param in the input stream * @param close true to close the input stream when done, false not to * @return the bytes * @throws IOException if there's a problem reading from the input stream */ public static byte[] toByteArray(InputStream in, boolean close) throws IOException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } return out.toByteArray(); } finally { if (close) { closeQuietly(in); } } } /** * Closes a closeable resource, catching its {@link IOException}. * @param closeable the resource to close (can be null) */ public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { //ignore } } }