Java FileInputStream Read readFile(String fname)

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

Description

read File

License

Apache License

Declaration

public static byte[] readFile(String fname) throws IOException 

Method Source Code

//package com.java2s;
/**//  w  ww . j a  va 2 s  .c  o m
 * Copyright 2014 
 * SMEdit https://github.com/StarMade/SMEdit
 * SMTools https://github.com/StarMade/SMTools
 *
 * 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.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    public static byte[] readFile(String fname) throws IOException {
        byte[] ret;
        try (FileInputStream fis = new FileInputStream(fname)) {
            ret = readStream(fis);
        }
        return ret;
    }

    public static byte[] readStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copy(is, baos);
        return baos.toByteArray();
    }

    public static void copy(InputStream is, OutputStream os) throws IOException {
        if (!(is instanceof BufferedInputStream)) {
            is = new BufferedInputStream(is);
        }
        if (!(os instanceof BufferedOutputStream)) {
            os = new BufferedOutputStream(os);
        }
        for (;;) {
            int ch = is.read();
            if (ch == -1) {
                break;
            }
            os.write(ch);
        }
        os.flush();
    }
}

Related

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