Java FileInputStream Read readFile(String path)

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

Description

Reads a given file into a byte array.

License

Apache License

Parameter

Parameter Description
path Path form where the file should be read.

Exception

Parameter Description
FileNotFoundException an exception
IOException an exception

Return

Byte array

Declaration

public static byte[] readFile(String path) throws FileNotFoundException, IOException 

Method Source Code


//package com.java2s;
/*/*from  w  w  w .  j  a v a2 s.co m*/
* Copyright 2012 the original author or authors.
*
* 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.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;

public class Main {
    /**
     * Reads a given file into a byte array.
     * 
     * @param path
     *            Path form where the file should be read.
     * @return Byte array
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static byte[] readFile(String path) throws FileNotFoundException, IOException {
        File fileToReade = new File(path);
        if (fileToReade.exists()) {
            byte[] buffer = new byte[(int) fileToReade.length()];
            FileInputStream inStream = null;
            try {
                inStream = new FileInputStream(fileToReade);
                inStream.read(buffer);
            } finally {
                try {
                    if (inStream != null)
                        inStream.close();
                } catch (IOException e) {
                    ;
                }
            }

            return buffer;
        } else {
            throw new FileNotFoundException("File " + path + "not found!");
        }
    }
}

Related

  1. readFile(String fname)
  2. readFile(String fname)
  3. readFile(String fname)
  4. readFile(String imageName)
  5. readFile(String name)
  6. Readfile(String path)
  7. readFile(String path)
  8. readFile(String path)
  9. readFile(String path)