Java SeekableByteChannel read entire file
import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class Main { public static void main(String[] args) { Path path = Paths.get("Main.java"); int bufferSize = 1024; try (SeekableByteChannel sbc = Files.newByteChannel(path, StandardOpenOption.READ)) { System.out.println("Contents of File"); sbc.position(0);/* ww w. j a v a 2 s. c om*/ ByteBuffer buffer = ByteBuffer.allocate(bufferSize); String encoding = System.getProperty("file.encoding"); int numberOfBytesRead = sbc.read(buffer); System.out.println("Number of bytes read: " + numberOfBytesRead); while (numberOfBytesRead > 0) { buffer.rewind(); System.out.print("[" + Charset.forName(encoding).decode(buffer) + "]"); buffer.flip(); numberOfBytesRead = sbc.read(buffer); System.out.println("\nNumber of bytes read: " + numberOfBytesRead); } } catch (Exception e) { e.printStackTrace(); } } }