Android FileInputStream Read fastStream(File file)

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

Description

fast Stream

License

Apache License

Declaration

public static InputStream fastStream(File file) 

Method Source Code

//package com.java2s;
/*/*from  w  w w.jav a  2s.  c  om*/
 Copyright (c) 2012 IBM Corp.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class Main {
    public static InputStream fastStream(File file) {
        if (file == null) {
            throw new IllegalArgumentException(
                    "Passed null file to fastStream");
        }
        FileChannel fc = null;
        byte[] bytes = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            fc = fis.getChannel();
            if (fc.size() > 100000000) {
                fc = null; //so finally clause won't screw us
                return fis;
            }
            MappedByteBuffer byteBuffer = fc.map(
                    FileChannel.MapMode.READ_ONLY, 0, fc.size());

            int size = byteBuffer.capacity();
            if (size > 0) {
                // Retrieve all bytes in the buffer
                byteBuffer.clear();
                bytes = new byte[size];
                byteBuffer.get(bytes, 0, bytes.length);
            } else {
                bytes = new byte[0];
            }

            fc.close();
            fc = null;
        } catch (FileNotFoundException fnfx) {
            System.err.println("File not found: " + fnfx);
        } catch (IOException iox) {
            System.err.println("I/O problems: " + iox);
        } finally {
            if (fc != null) {
                try {
                    fc.close();
                } catch (IOException ignore) {
                    // ignore
                }
            }
        }
        return new ByteArrayInputStream(bytes);
    }
}

Related

  1. readSomeDataFromFile(String path, byte[] data)
  2. getCredentials(FileInputStream fis)