This discussion is archived
5 Replies Latest reply: Oct 31, 2009 5:09 PM by 843790 RSS

FileChannel and RandomAccessFile close

843790 Newbie
Currently Being Moderated
Hello,
I am using FileChannel trylock() on my files prior to writing to them. To get the FileChannel object on file, i using RandomAccessFile,
My code looks likes this
public static FileChannel fileChannel(File file, Mode mode) throws IOException {
    FileChannel rfc = null;
    RandomAccessFile raf;
    switch (mode) {
      case RA:
        raf = new RandomAccessFile(file, mode.string());
        rfc = raf.getChannel();
        rfc.position(raf.length()); //ready for append
        break;
      case APPEND:
        FileOutputStream fos = new FileOutputStream(file, true);
        rfc = fos.getChannel();
        break;
      default:
        raf = new RandomAccessFile(file, mode.string());
        rfc = raf.getChannel();
    }

    return rfc;
  }
and
public static voif getLock(File lockFile){
 FileChannel fc = null;
FileLock lock=null;
    try {
      fc = FileUtil.fileChannel(lockFile, FileUtil.RW); <-- I m not calling close on fileChannel.
      lock = fc.tryLock(0L, Long.MAX_VALUE, shared);
    } catch (IOException e) {
        logger.severe("FILE_LOCK_FAILED");
    }
return lock;
}
After getting the file channel object on the file, the objects created in the above fileChannel method are of no use, but my worry is that i m not calling close on any of these objects inside the fileChannel method.
And even i m not calling close on the fileChannel return by this method anywhere.
Is it necessary to call close on fileChannel object, RandomAccessFile object and FileOutputStream object. If true, then is there any order i have to follow?
Is closing FIleLock enough in the end?