JAVA – codewindow.in

Related Topics

JAVA Programing

In this example, a ByteBuffer is allocated with a size of 1024 bytes. A FileChannel is opened for the file “file.txt”. The channel is then read into the buffer, which is then flipped and printed to the console. Finally, the buffer is cleared and the channel and file are closed.

Overall, the Buffer and Channel classes in Java NIO provide a more efficient and flexible way to handle I/O operations, making it easier to handle large amounts of data or multiple connections.

In this example, we open a file called “example.txt” for reading and writing using a RandomAccessFile. We then get a FileChannel object from the file using the getChannel() method.

To write data to the file, we first create a ByteBuffer with the same length as the data we want to write. We then put the bytes of the data into the buffer, flip the buffer to prepare it for writing, and use the write() method of the channel to write the data to the file.

To read data from the file, we first clear the buffer and set the position of the channel to the beginning of the file using the position() method. We then use the read() method of the channel to read the data from the file into the buffer, flip the buffer to prepare it for reading, and get the bytes from the buffer into a byte array. We then convert the byte array to a string and print it to the console.

Finally, we close the channel and file using the close() method.

      

Popular Category

Topics for You

Go through our study material. Your Job is awaiting.

Categories