Java FileInputStream Read readFile(File file, String encoding)

Here you can find the source of readFile(File file, String encoding)

Description

read File

License

Apache License

Declaration

public static String readFile(File file, String encoding) throws IOException 

Method Source Code

//package com.java2s;
/**//from w  w w  .j a  va  2s  .  com
 *  Copyright 2009 Welocalize, Inc. 
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  
 *  You may obtain a copy of the License at 
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  
 */

import java.io.File;

import java.io.FileInputStream;

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

public class Main {
    public static byte[] readFile(File file, int size) throws IOException {
        return readFile(new FileInputStream(file), size);
    }

    /**
     * Reads bytes from given input stream with specified length.
     */
    public static byte[] readFile(InputStream in, int size) throws IOException {
        byte[] b = new byte[size];
        try {
            in.read(b, 0, size);
        } finally {
            if (in != null) {
                in.close();
            }
        }

        return b;
    }

    public static String readFile(File file) throws IOException {
        FileInputStream in = null;

        try {
            in = new FileInputStream(file);
            byte[] b = new byte[in.available()];
            in.read(b, 0, b.length);
            return new String(b);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public static String readFile(File file, String encoding) throws IOException {
        return readFile(new FileInputStream(file), encoding);
    }

    /**
     * Reads the given input stream to a string content.
     */
    public static String readFile(InputStream in, String encoding) throws IOException {
        try {
            byte[] b = new byte[in.available()];
            in.read(b);
            return new String(b, encoding);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

Related

  1. readFile(File file)
  2. readFile(File file)
  3. readFile(File file, boolean compress)
  4. readFile(File file, int size)
  5. readFile(File file, OutputStream output)
  6. readFile(File file, String encoding)
  7. readFile(File file, String encoding)
  8. readFile(File fyl)
  9. readFile(File path)