Java examples for File Path IO:Text File
Processing the contents of the entire file
import java.io.IOException; 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) throws IOException { int bufferSize = 8; Path path = Paths.get("/home/docs/users.txt"); final String newLine = System.getProperty("line.separator"); try (SeekableByteChannel sbc = Files.newByteChannel(path, StandardOpenOption.WRITE)) { ByteBuffer buffer;//w w w . j av a 2s . co m System.out.println("Contents of File"); sbc.position(0); 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); } } } }