Read a string value from the specified file - Android File Input Output

Android examples for File Input Output:InputStream

Description

Read a string value from the specified file

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;

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

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

public class Main {
    private static final int BUFSIZ = 4096;

    /**/* w  w  w.  jav  a 2s  .com*/
     * Read a string value from the specified file
     * 
     * @param file
     *            The target file
     * @return A string value
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String readAsString(final File file)
            throws FileNotFoundException, IOException {
        return readAsString(file.getAbsolutePath());
    }

    /**
     * Read a string value from the specified path
     * 
     * @param path
     *            The target file path
     * @return A string value
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String readAsString(final String path)
            throws FileNotFoundException, IOException {
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(path);
            return readAsString(fis);
        } finally {
            closeQuietly(fis);
        }
    }

    /**
     * Read a string value from the specified input stream
     * 
     * @param is
     *            The target input stream
     * @return A string value
     * @throws IOException
     */
    public static String readAsString(final InputStream is)
            throws IOException {
        final byte[] buf = new byte[BUFSIZ];
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        for (int n = 0; (n = is.read(buf)) > 0;) {
            baos.write(buf, 0, n);
        }

        return baos.toString();
    }

    /**
     * Close the closeables quietly
     * 
     * @param closeables
     *            Instances of {@link Closeable}
     */
    public static void closeQuietly(final Closeable... closeables) {
        if (null == closeables || closeables.length <= 0)
            return;

        for (int i = 0; i < closeables.length; i++) {
            final Closeable closeable = closeables[i];
            if (null == closeable)
                continue;

            try {
                closeables[i].close();
            } catch (IOException e) {
            }
        }
    }
}

Related Tutorials