Read an integer value from the specified file - Android File Input Output

Android examples for File Input Output:InputStream

Description

Read an integer value from the specified file

Demo Code


//package com.java2s;

import java.io.Closeable;
import java.io.DataInputStream;

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

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

public class Main {
    /**/*from   w ww .ja v a2  s.c o  m*/
     * Read an integer value from the specified file
     * 
     * @param file
     *            The target file
     * @return An integer value
     * @throws IOException
     */
    public static int readAsInt(final File file) throws IOException {
        return readAsInt(file.getAbsolutePath());
    }

    /**
     * Read an integer value from the specified path
     * 
     * @param path
     *            The target file path
     * @return An integer value
     * @throws IOException
     */
    public static int readAsInt(final String path) throws IOException {
        FileInputStream fis = null;

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

    /**
     * Read an integer value from the specified path
     * 
     * @param path
     *            The target file path
     * @return An integer value
     * @throws IOException
     */
    public static int readAsInt(final InputStream in) throws IOException {
        return new DataInputStream(in).readInt();
    }

    /**
     * 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