Java tutorial
import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; 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; public class Main { public static void main(String[] args) { Path src = Paths.get("test.txt"); String encoding = System.getProperty("file.encoding"); Charset cs = Charset.forName(encoding); try (SeekableByteChannel seekableChannel = Files.newByteChannel(src, READ, WRITE, CREATE, TRUNCATE_EXISTING)) { printDetails(seekableChannel, "Before writing data"); writeData(seekableChannel, cs); printDetails(seekableChannel, "After writing data"); seekableChannel.position(0); printDetails(seekableChannel, "After resetting position to 0"); readData(seekableChannel, cs); printDetails(seekableChannel, "After reading data"); } catch (IOException e) { e.printStackTrace(); } } public static void writeData(SeekableByteChannel seekableChannel, Charset cs) throws IOException { String separator = System.getProperty("line.separator"); StringBuilder sb = new StringBuilder(); sb.append("test"); sb.append(separator); sb.append("test2"); sb.append(separator); CharBuffer charBuffer = CharBuffer.wrap(sb); ByteBuffer byteBuffer = cs.encode(charBuffer); seekableChannel.write(byteBuffer); } public static void readData(SeekableByteChannel seekableChannel, Charset cs) throws IOException { ByteBuffer byteBuffer = ByteBuffer.allocate(128); String encoding = System.getProperty("file.encoding"); while (seekableChannel.read(byteBuffer) > 0) { byteBuffer.rewind(); CharBuffer charBuffer = cs.decode(byteBuffer); System.out.print(charBuffer); byteBuffer.flip(); } } public static void printDetails(SeekableByteChannel seekableChannel, String msg) { try { System.out.println( msg + ": Size = " + seekableChannel.size() + ", Position = " + seekableChannel.position()); } catch (IOException e) { e.printStackTrace(); } } }