Java DataInputStream Read readBytes(String filename)

Here you can find the source of readBytes(String filename)

Description

read Bytes

License

Open Source License

Declaration

public static byte[] readBytes(String filename) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

import java.io.IOException;

public class Main {
    public static byte[] readBytes(String filename) {
        File fileTxt = new File(filename);

        if (!fileTxt.exists()) {
            System.out.println("Erro ao abrir arquivo:\n" + fileTxt.getAbsolutePath());
            return null;
        }/*from  w  ww .  jav  a  2  s  . com*/

        try {
            int size = (int) fileTxt.length();
            byte[] bytes = new byte[size];
            int read = 0;
            int numRead = 0;

            DataInputStream dis = new DataInputStream(new FileInputStream(fileTxt));

            while (read < bytes.length && (numRead = dis.read(bytes, read, bytes.length - read)) >= 0) {
                read = read + numRead;
            }

            if (read < bytes.length) {
                System.out.println("Erro ao ler: " + fileTxt.getName());
            }

            dis.close();

            return bytes;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

Related

  1. readBytes(DataInputStream input, int size)
  2. readBytes(DataInputStream stream, int size)
  3. readBytes(DataInputStream stream, int size)
  4. readBytes(File ff)
  5. readBytes(String filename)
  6. readBytesArray(DataInputStream dis)
  7. readFromFile(File file)
  8. readFromFileToLineArray(File file)
  9. saveDoubleMatrixFromBinary(DataInputStream reader, int rows, int cols, PrintStream out)