Java File Read getFileContent(File file, int bufferSize)

Here you can find the source of getFileContent(File file, int bufferSize)

Description

get the content of the file

License

Apache License

Parameter

Parameter Description
file target file
bufferSize the buffer size

Exception

Parameter Description
FileNotFoundException , IOException

Return

String the file content

Declaration

public static String getFileContent(File file, int bufferSize) throws FileNotFoundException, IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;

import java.io.EOFException;
import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**//from   w  w  w  . ja va  2s .  c  o m
     * get the content of the file
     * 
     * @param file
     *            target file
     * @param bufferSize
     *            the buffer size
     * @return String the file content
     * @throws FileNotFoundException
     *             , IOException
     */
    public static String getFileContent(File file, int bufferSize) throws FileNotFoundException, IOException {

        StringBuffer strBuffer = new StringBuffer();
        BufferedReader in = new BufferedReader(new FileReader(file), bufferSize);
        String tempStr = in.readLine();
        strBuffer.append(tempStr);
        while ((tempStr = in.readLine()) != null) {
            strBuffer.append("\n").append(tempStr);
        }
        in.close();
        return strBuffer.toString();
    }

    /**
     * get the content of the file with defalut buffer size 1024
     * 
     * @param file
     *            target file
     * @return String the file content
     * @throws FileNotFoundException
     *             , IOException
     */
    public static String getFileContent(File file) throws FileNotFoundException, IOException {
        return getFileContent(file, 1024);
    }

    /**
     *** Reads a single line of characters from the specified InputStream,
     * terminated by either a newline (\n) or carriage-return (\r)
     *** 
     * @param input
     *            The InputStream
     *** @return The line read from the InputStream
     **/
    public static String readLine(InputStream input) throws IOException {
        StringBuffer sb = new StringBuffer();
        while (true) {
            int ch = input.read();
            if (ch < 0) { // eof
                throw new EOFException("End of InputStream");
            } else if ((ch == '\r') || (ch == '\n')) {
                return sb.toString();
            }
            sb.append((char) ch);
        }
    }
}

Related

  1. getFileContent(File pFile)
  2. getFileContent(final File f)
  3. getFileContent(final File file)
  4. getFileContent(final File srcFile)