read Bytes From File - Java File Path IO

Java examples for File Path IO:Binary File

Description

read Bytes From File

Demo Code


//package com.java2s;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] argv) throws Exception {
        File grammarFile = new File("Main.java");
        System.out.println(java.util.Arrays
                .toString(readBytesFromFile(grammarFile)));
    }/*from   w w w  . j ava2  s  .co  m*/

    /**
     * @param grammarFile
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static byte[] readBytesFromFile(File grammarFile)
            throws FileNotFoundException, IOException {
        byte[] oldBytes = null;
        if (grammarFile.exists()) {
            FileReader reader = new FileReader(grammarFile);
            ByteArrayOutputStream oldBytesStream = new ByteArrayOutputStream();
            while (reader.ready()) {
                oldBytesStream.write(reader.read());
            }
            oldBytesStream.flush();
            oldBytes = oldBytesStream.toByteArray();
            oldBytesStream.close();
        }
        return oldBytes;
    }
}

Related Tutorials