Java FileInputStream Read readFile(File file)

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

Description

read File

License

Open Source License

Declaration

public static final String readFile(File file) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 McGill University/* w w w  .  j a  v a 2 s  .c om*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Name - Initial Contribution
 *******************************************************************************/

import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
    public static final String readFile(File file) {
        BufferedInputStream bin = null;
        StringBuilder builder = new StringBuilder();

        try {
            // create FileInputStream object
            FileInputStream fin = new FileInputStream(file);

            // create object of BufferedInputStream
            bin = new BufferedInputStream(fin);

            // create a byte array
            byte[] contents = new byte[1024];

            int bytesRead = 0;
            while ((bytesRead = bin.read(contents)) != -1) {

                builder.append(new String(contents, 0, bytesRead));
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            // close the BufferedInputStream using close method
            try {
                if (bin != null)
                    bin.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }

        }

        return builder.toString();

    }
}

Related

  1. readFile(File f, int fetchLength, byte[] bytes)
  2. readFile(File f, int iChunkSize)
  3. readFile(File file)
  4. readFile(File file)
  5. readFile(File file)
  6. readFile(File file)
  7. readFile(File file)
  8. readFile(File file)
  9. readFile(File file)