Hello Experts,
I am trying to use File lock in my GUI (which is deployed as Web Start
Application) to prevent concurrency issues.
However it does not work, I have below sample mentod:
void writeIntoTheFile(XSSFWorkbook defectWorkBook, File fileToWrite) {
logger.debug("In writeIntoTheFile");
//Without file locking code - works well
/* try{
FileOutputStream out = new FileOutputStream(fileToWrite.getPath());
defectWorkBook.write(out);
out.close();
}catch(IOException e){logger.debug("Here is error message" +
e.getMessage());} */
FileLock lock = null;
FileChannel channel = null;
FileOutputStream out = null;
try {
channel = new RandomAccessFile(fileToWrite,
"rw").getChannel();
logger.debug("trying to get the lock...");
try{
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
System.out.println("File is already locked" +
e.getMessage());
}
if (lock != null) {
logger.debug("Got the lock to write into the file...");
*out = new FileOutputStream(fileToWrite.getPath());*
<<<<< file gets corrupted here
logger.debug("about to write in the file...");
defectWorkBook.write(out);
logger.debug("written..");
} else {
logger.debug("Another instance is already running");
JOptionPane.showMessageDialog(null, "Another instance is
already writing, Try after a few seconds.", "Write Error...",
JOptionPane.INFORMATION_MESSAGE);
}
logger.debug("about to close the file...");
out.close();
logger.debug("closed..");
} catch (Exception e) {
//logger.debug(e.printStackTrace());
System.out.println("Here is message" + e.getMessage());
e.printStackTrace();
}
try{
if (lock != null && lock.isValid()) {
logger.debug("about to release the lock...");
lock.release();
logger.debug("lock released...");
}
channel.close();
}catch(IOException e){logger.debug("Here is error message" +
e.getMessage());}
}
In the above code, there is no exception thrown and all the debug statements
are displayed on the screen. However, if I try to append some records (data
fetched from data source) in existing XLSX workbook then whole workbook gets
corrupted. I checked it while debugging the application.And I found it
happens here
*out = new FileOutputStream(fileToWrite.getPath());
*then I passed true for append
*out = new FileOutputStream(fileToWrite.getPath(), true);
*
now above method executes correctly and while debugging I can see the values
in the rows and cells of MS excel workbook sheet (defectWorkBook), but
somehow they are not written on this statement defectWorkBook.write(out); No
exception is thrown at all. not sure why its not written in the actual file.
Can you please help me if I am really missing something?
Many Thanks in advance,
rahul