Update
Followings are the changes that I have made as per the review:
To read the file:
RandomAccessFile serFile = null;
FileChannel fileChannel = null;
try {
serFile = new RandomAccessFile(file, "rw");
fileChannel = serFile.getChannel();
FileLock lock = fileChannel.lock();
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(Channels.newInputStream(fileChannel));
return clazz.cast(objectInputStream.readObject());
} catch (Exception cause) {
cause.printStackTrace();
} finally {
lock.release();
closeStream(objectInputStream);
}
} catch (Exception cause) {
cause.printStackTrace();
} finally {
closeStream(fileChannel);
closeStream(serFile);
}
To write the file:
RandomAccessFile serFile = null;
FileChannel fileChannel = null;
try {
serFile = new RandomAccessFile(file, "rw");
fileChannel = serFile.getChannel();
FileLock lock = fileChannel.lock();
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(Channels.newOutputStream(fileChannel));
objectOutputStream.writeObject(serialized);
} catch (Exception cause) {
cause.printStackTrace();
} finally {
lock.release();
closeStream(objectOutputStream);
}
} catch (Exception cause) {
cause.printStackTrace();
} finally {
closeStream(fileChannel);
closeStream(serFile);
}