Friday, 29 January 2016

Java Dynamic Proxy

Proxy is a design pattern. We create and use proxy objects when we want to add or modify some functionality of an already existing class. The proxy object is used instead of the original one. Usually the proxy objects have the same methods as the original one and in Java proxy classes usually extend the original class. The proxy has a handle to the original object and can call the method on that.

This way proxy classes can implement many things in a convenient way:
  • logging when a method starts and stops
  • perform extra checks on arguments
  • mocking the behavior of the original class
  • implement lazy access to costly resources

Tuesday, 12 January 2016

Reading/Writing to/from Files using FileChannel and ByteBuffer in Java

In the past, I have talked about RandomAccessFile and how it can be used for doing faster IO in Java, and in this Java NIO tutorial, we are going to see how to use read/write data from using FileChannel and ByteBuffer.

Channel provides an alternate way to read data from a file, it provides better performance than InputStream or OutputStream. It can also be opened in blocking and non-blocking mode. Though, FileChannles are read/write channels and they are always blocking, they cannot be put into non-blocking mode. The RandomAccessFile class treats a file as an array of Bytes.

You can write your data in any position of the Array and you can read from any position. To do that, it uses a pointer that holds the current position and provides several methods like seek() to move that pointer. Once you are at the right position, you can get the FileChannel from RandomAccessFile and starting reading data from a file. By the way, JDK 7 also introduced NIO 2, which makes dealing with files and directory even easier.