Java FileReader Read readFile(File iFile)

Here you can find the source of readFile(File iFile)

Description

read File

License

MIT License

Declaration

static public String readFile(File iFile) throws IOException 

Method Source Code


//package com.java2s;
/*// w w w.ja  va 2s.c o  m
 * Copyright (c) 2010 Patrick Mueller
 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;

public class Main {
    static private final int DEFAULT_BUFFER_SIZE = 256 * 256 - 400;

    /**
     * 
     */
    static public String readFile(String iFileName) throws IOException {
        return readFile(new File(iFileName));
    }

    /**
     * 
     */
    static public String readFile(File iFile) throws IOException {
        if (!iFile.exists())
            throw new FileNotFoundException("file not found: " + iFile.getAbsolutePath());

        long iFileLength = iFile.length();

        if (0 == iFileLength)
            return "";
        int bufferSize = (int) Math.min(iFileLength, (long) DEFAULT_BUFFER_SIZE);

        FileReader fr = new FileReader(iFile);
        String result = readStream(fr, bufferSize);
        fr.close();

        return result;
    }

    /**
     * 
     */
    static public String readStream(Reader rStream, int bufferSize) throws IOException {
        if (bufferSize <= 0)
            bufferSize = DEFAULT_BUFFER_SIZE;
        bufferSize = Math.min(bufferSize, DEFAULT_BUFFER_SIZE);

        char[] buffer = new char[bufferSize];
        StringWriter sr = new StringWriter(bufferSize);

        int read;
        while ((read = rStream.read(buffer)) > 0) {
            sr.write(buffer, 0, read);
        }

        return sr.toString();
    }
}

Related

  1. readFile(File file)
  2. readFile(File file)
  3. readFile(File file)
  4. readFile(File file)
  5. readFile(File file)
  6. readFile(final String fileName)
  7. readFile(Reader reader)
  8. readFile(String file)
  9. readFile(String file)