问题
With your suggestions given on this thread,
I tried using FileLock, however, when I write something in the file, somehow excel file gets corrupted and there is nothing in the file (it gets empty, no contents in there)
I have the following method:
void writeIntoTheFile(XSSFWorkbook defectWorkBook, File fileToWrite) {
FileLock lock = null;
FileChannel channel = null;
FileOutputStream out = null;
try {
//fileToWrite contains an excel .xlsx file
channel = new RandomAccessFile(fileToWrite, "rw").getChannel();
lock = channel.tryLock();
if (lock != null) {
out = new FileOutputStream(fileToWrite.getPath());
defectWorkBook.write(out);
} else {
JOptionPane.showMessageDialog(null, "Another instance is already writing, Try after a few seconds.", "Write Error...", JOptionPane.INFORMATION_MESSAGE);
}
out.close();
} catch (Exception e) {
e.getMessage();
}
finally{
if (lock != null && lock.isValid()) {
lock.release();
}
channel.close();
}
}
Seems the problem is coming from below code:
channel = new RandomAccessFile(fileToWrite, "rw").getChannel();
lock = channel.tryLock();
Can anyone please help me on this issue?
rahul
回答1:
I suspect you are getting an exception in your try{} block, but your catch clock doesn't prin it. e.getMessage() will get the message but not print it.
I suggest something along the lines of e.printStackTrace() (for a production system you would want to do something more useful with the exception).
来源:https://stackoverflow.com/questions/7736530/part-2-web-start-application-concurrency-issue