Java Path File Read nio readFile(Path path)

Here you can find the source of readFile(Path path)

Description

Fully reads a file into a byte array.

License

Open Source License

Parameter

Parameter Description
path the path to the file to read.

Exception

Parameter Description
IOException if an error occurs in the process.

Return

the bytes read from the file.

Declaration

public static byte[] readFile(Path path) throws IOException 

Method Source Code


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

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    private final static int BUFFER_SIZE = 16384;

    /**//from   w w  w.  j  a v a2 s  .  c  o m
     * Fully reads a file into a byte array.
     *
     * @param path the path to the file to read.
     * @return the bytes read from the file.
     * @throws IOException if an error occurs in the process.
     */
    public static byte[] readFile(Path path) throws IOException {
        try (final InputStream in = Files.newInputStream(path)) {
            return readStream(in);
        }
    }

    /**
     * Fully reads an input stream into a byte array.
     * <p/>
     * This method does not close the stream when done.
     *
     * @param inputStream the input stream to read.
     * @return the bytes read from the stream.
     * @throws IOException if an error occurs in the process.
     */
    public static byte[] readStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);

        for (int n = inputStream.read(buffer); n > 0; n = inputStream.read(buffer))
            out.write(buffer, 0, n);

        return out.toByteArray();
    }
}

Related

  1. reader(String path)
  2. readers(String path)
  3. readFile(Path directory, String... parts)
  4. readFile(Path file)
  5. readFile(Path path)
  6. readFile(String path)
  7. readFile(String path)
  8. readFile(String path)
  9. readFile(String path)