Java InputStreamReader Read readFile(File target)

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

Description

Return a buffer containing the contents of the file at the specified location.

License

Open Source License

Parameter

Parameter Description
target the file

Exception

Parameter Description
IOException an exception

Return

StringBuffer

Declaration

static public StringBuffer readFile(File target) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2000, 2010 IBM Corporation and others.
 * 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:/* w  ww  .ja va  2 s  .com*/
 *      IBM Corporation - initial API and implementation
 *******************************************************************************/

import java.io.*;

import java.util.zip.ZipFile;

public class Main {
    /**
     * Return a buffer containing the contents of the file at the specified location.
     * 
     * @param target the file
     * @return StringBuffer
     * @throws IOException
     */
    static public StringBuffer readFile(File target) throws IOException {
        return readFile(new FileInputStream(target));
    }

    static public StringBuffer readFile(InputStream stream) throws IOException {
        InputStreamReader reader = new InputStreamReader(new BufferedInputStream(stream));
        StringBuffer result = new StringBuffer();
        char[] buf = new char[4096];
        int count;
        try {
            count = reader.read(buf, 0, buf.length);
            while (count != -1) {
                result.append(buf, 0, count);
                count = reader.read(buf, 0, buf.length);
            }
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore exceptions here
            }
        }
        return result;
    }

    public static void close(Object obj) {
        if (obj == null)
            return;
        try {
            if (obj instanceof InputStream)
                ((InputStream) obj).close();
            else if (obj instanceof ZipFile)
                ((ZipFile) obj).close();
            else if (obj instanceof OutputStream)
                ((OutputStream) obj).close();
        } catch (IOException e) {
            //boo
        }
    }
}

Related

  1. readFile(File file, String encoding)
  2. readFile(File file, String encoding)
  3. readFile(File filename)
  4. readFile(File path)
  5. readFile(File resultFile)
  6. readFile(FileInputStream file)
  7. readFile(final File file)
  8. readFile(final File inputFile)
  9. readFile(final String aFileName)