根据您在 this thread 上给出的建议,
我尝试使用FileLock,但是,当我在文件中写入内容时,Excel文件不知何故被损坏,并且文件中没有任何内容(它变空,其中没有内容)
我有以下方法:
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();
}
}
问题似乎来自以下代码:
channel = new RandomAccessFile(fileToWrite, "rw").getChannel();
lock = channel.tryLock();
有人可以帮我解决这个问题吗?
拉胡尔
最佳答案
我怀疑您的 try{} block 中出现异常,但您的 catch 时钟没有打印它。 e.getMessage() 将获取消息但不会打印它。
我建议遵循e.printStackTrace()的做法(对于生产系统,您可能会想做一些更有用的异常(exception))。
关于java - 第 2 部分 : Web Start Application: Concurrency Issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7736530/