Java FileInputStream Read readFile(String filename)

Here you can find the source of readFile(String filename)

Description

read File

License

Open Source License

Declaration

public static String readFile(String filename) throws Exception 

Method Source Code

//package com.java2s;
/**/*from w  w w.j  av  a 2  s . c  om*/
 * Copyright 2009, Google Inc.  All rights reserved.
 * Licensed to PSF under a Contributor Agreement.
 */

import java.io.File;
import java.io.FileInputStream;

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

public class Main {
    private static final String UTF_8 = "UTF-8";

    public static String readFile(String filename) throws Exception {
        return readFile(new File(filename));
    }

    public static String readFile(File path) throws Exception {
        // Don't use line-oriented file read -- need to retain CRLF if present
        // so the style-run and link offsets are correct.
        return new String(getBytesFromFile(path), UTF_8);
    }

    public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = null;

        try {
            is = new FileInputStream(file);
            long length = file.length();
            if (length > Integer.MAX_VALUE) {
                throw new IOException("file too large: " + file);
            }

            byte[] bytes = new byte[(int) length];
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                    && (numRead = is.read(bytes, offset, bytes.length
                            - offset)) >= 0) {
                offset += numRead;
            }
            if (offset < bytes.length) {
                throw new IOException("Failed to read whole file " + file);
            }
            return bytes;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}

Related

  1. readFile(String filename)
  2. readFile(String filename)
  3. readFile(String filename)
  4. readFile(String fileName)
  5. readFile(String fileName)
  6. readFile(String filename)
  7. readFile(String filename)
  8. readFile(String fileName)
  9. readFile(String fileName, String charset)