Код: Выделить всё
public class CodingDecoding
{
public static void main(String[] args)
{
try (
FileChannel out = FileChannel.open(Paths.get("out.txt"),
StandardOpenOption.READ,
StandardOpenOption.WRITE,
StandardOpenOption.CREATE);
FileChannel in = FileChannel.open(Paths.get("in.txt"),
StandardOpenOption.READ,
StandardOpenOption.WRITE,
StandardOpenOption.CREATE);
)
{
// write "Hello" to buffer and flip to make buffer ready for writing
ByteBuffer buffer = ByteBuffer.allocate(1000);
buffer.put("Hello".getBytes());
System.out.println(buffer); // [pos=5 lim=1000 cap=1000]
buffer.flip();
System.out.println(buffer); // [pos=0 lim=5 cap=1000]
// write
in.write(buffer);
System.out.println(buffer); //[pos=5 lim=5 cap=1000]
// flip for reading
buffer.flip();
System.out.println(buffer); //[pos=0 lim=5 cap=1000]
// read
in.read(buffer);
System.out.println(buffer);// [pos=0 lim=5 cap=1000] why pos=0 not pos=5? I didn't read anything?
// flip for writing
buffer.flip();
System.out.println(buffer); //[pos=0 lim=0 cap=1000] so I write nothing to out
out.write(buffer);
}
catch (IOException ioException)
{
ioException.printStackTrace();
}
}
}
Я пытался написать «Привет» на вход, затем прочитать оттуда и, наконец, написать на выход. . Но я не понимаю, почему после чтения позиция буфера = 0. Как будто я ничего не читал?
Источник: https://stackoverflow.com/questions/781 ... after-read