Java File Read via ByteBuffer readBytes(Path file)

Here you can find the source of readBytes(Path file)

Description

Read bytes from a path

License

LGPL

Parameter

Parameter Description
file The file to read from

Exception

Parameter Description
IOException an exception

Return

the bytes read

Declaration

public static byte[] readBytes(Path file) throws IOException 

Method Source Code


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

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class Main {
    /**/*from   w w w. j  av  a 2 s  . c  om*/
     * Read bytes from a path
     * @param file The file to read from
     * @return the bytes read
     * @throws IOException
     */
    public static byte[] readBytes(Path file) throws IOException {
        SeekableByteChannel channel = Files.newByteChannel(file, StandardOpenOption.READ);
        ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
        channel.read(buffer);

        return (byte[]) buffer.flip().array();
    }

    @Deprecated
    public static byte[] readBytes(File file) throws IOException {
        Integer length = (int) file.length();
        byte[] output = new byte[length];
        Integer offset = 0;

        InputStream in = new FileInputStream(file);

        while (offset < length) {
            offset += in.read(output, offset, (length - offset));
        }

        in.close();

        return output;
    }

    public static String read(Path file) throws IOException {
        return utf8(readBytes(file));
    }

    @Deprecated
    public static String read(File file) throws IOException {
        return utf8(readBytes(file));
    }

    public static byte[] utf8(String string) {
        try {
            return string.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String utf8(byte[] bytes) {
        try {
            return new String(bytes, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. readByte(String filePath)
  2. readBytes(File f)
  3. readBytes(final InputStream in, final int length)
  4. readBytes(final String file)
  5. readBytes(InputStream is)
  6. readBytes(ReadableByteChannel channel, byte[] array)
  7. readBytes(String file)
  8. readCode(byte[] message)
  9. readColumnarKeyBlockDataForNoDictionaryCols(byte[] columnarKeyBlockData)