Read data from Java ByteBuffer

Asked 2 years ago, Updated 2 years ago, 23 views

Scanner sc = new Scanner(System.in);

System.out.print("Source File: ");
Path src = Paths.get(sc.nextLine());

System.out.print("Copy Name: ");
Path dst = Paths.get(sc.nextLine());

ByteBuffer buff = ByteBuffer.allocate(1024);

try (FileChannel rc = FileChannel.open(src, StandardOpenOption.READ);
     FileChannel wc = FileChannel.open(dst, StandardOpenOption.WRITE)) {
    int num;

    while (true) {
        num = rc.read(buff); <--- !

        if (num == -1) {
          break;
        }

        buff.flip();
        wc.write(buff);

        buff.clear(); <--- !
    }

} } catch (IOException e) {
    e.printStackTrace();
}

Code to copy the original file to a different name.

Here buff.Clearing the clear() method creates an infinite loop. What I'm curious about is why an infinite loop occurs.

buff.When clear() is called, the read() method at the top of the while statement returns -1 when the file is finished reading. So break is done by the if statement.

But buff.If clear() is not invoked, the read() method returns 0 to avoid getting caught in the if statement.

What is the difference between returning -1 and 0? And I wonder what this has to do with the clear() method.

java

2022-09-21 18:53

1 Answers

You'll understand if you learn the basics of stream processing.

Description of the read method. If you look at the description of the return value, the return value is the number of bytes read. So if you didn't empty the buffer...The buffer is full and cannot be read and saved further. This means that the number of bytes read is zero.

Also, zero result means that there is more to read through that stream.

The buffer must be empty before read can read the bytes and write them to the buffer and return the size.

public abstract int read(ByteBuffer dst)
                  throws IOException
Reads a sequence of bytes from this channel into the given buffer.
Bytes are read starting at this channel's current file position, and then the file position is updated with the number of bytes actually read. Otherwise this method behaves exactly as specified in the ReadableByteChannel interface.

Specified by:
read in interface ReadableByteChannel
Specified by:
read in interface SeekableByteChannel
Parameters:
dst - The buffer into which bytes are to be transferred
Returns:
The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream
Throws:
ClosedChannelException - If this channel is closed
AsynchronousCloseException - If another thread closes this channel while the read operation is in progress
ClosedByInterruptException - If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt status
IOException - If some other I/O error occurs


2022-09-21 18:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.