Java File Read via ByteBuffer read(Path file)

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

Description

read

License

LGPL

Declaration

public static String read(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 {
    public static String read(Path file) throws IOException {
        return utf8(readBytes(file));
    }//from  w w  w .  j  a  v  a  2s .c o m

    @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;
        }
    }

    /**
     * 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;
    }
}

Related

  1. read(File from)
  2. read(final File source)
  3. read(final FileChannel channel)
  4. read(final Reader input, final char[] buffer, final int offset, final int length)
  5. read(InputStream stream)
  6. read(Path file, int pos, int length)
  7. read(Reader reader)
  8. read24BitInteger(byte[] threeBytes, ByteOrder order)
  9. read_file(File input)