Here you can find the source of getFileContentAsString(File file, String encoding)
Parameter | Description |
---|---|
file | the file to get the content |
Parameter | Description |
---|---|
IOException | is some problem occur while reading from file. |
public static String getFileContentAsString(File file, String encoding) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class Main { /**// w w w.ja v a2 s. c o m * File read buffer size. */ private static final int BUFFER_SIZE = 4096; /** * Get the content (as string) of the given file. * * @param file * the file to get the content * @return the content of the file as string * @throws IOException * is some problem occur while reading from file. */ public static String getFileContentAsString(File file, String encoding) throws IOException { return new String(getFileContentAsBytes(file), encoding); } /** * Get the content (as string) of the given file. * * @param file * the file to get the content * @return the content of the file as string * @throws IOException * is some problem occur while reading from file. */ public static String getFileContentAsString(File file) throws IOException { return getFileContentAsString(file, "UTF-8"); } /** * Get the content of the given file (as byte[]). * * @param file * the file to get content. * @return the content of the file as byte[]. * @throws IOException * if some problem occur while reading file */ public static byte[] getFileContentAsBytes(File file) throws IOException { if (file == null || !file.exists() || !file.canRead()) { throw new IllegalArgumentException( "Can't read the given file: " + (file == null ? null : file.getAbsoluteFile())); } byte[] data = new byte[(int) file.length()]; FileInputStream fis = null; try { fis = new FileInputStream(file); int offset = 0; int readCharacteres = 0; while ((readCharacteres = fis.read(data, offset, fis.available() >= BUFFER_SIZE ? BUFFER_SIZE : fis.available())) > 0) { offset += readCharacteres; } } finally { if (fis != null) { fis.close(); } } return data; } }