Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static byte[] readFileToMemory(String file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        FileChannel fileChannel = fis.getChannel();
        long size = fileChannel.size();
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
        byte[] data = new byte[(int) size];
        mappedByteBuffer.get(data, 0, (int) size);
        fileChannel.close();
        fis.close();
        return data;
        //      return readFileToMemory(new File(file));
    }

    public static byte[] readFileToMemory(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        byte[] data = new byte[(int) file.length()];
        int start = 0;
        int read = 0;
        while ((read = bis.read(data, start, data.length - start)) > 0) {
            start += read;
        }
        bis.close();
        fis.close();
        return data;
    }

    public static void close(Closeable closable) {
        if (closable != null) {
            try {
                closable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}