第2部分:Web Start应用程序:并发问题

时间:2011-10-12 07:19:30

标签: java file locking

根据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();

有人可以帮我解决这个问题吗?

的Rahul

1 个答案:

答案 0 :(得分:0)

我怀疑你在try {}区块中遇到异常,但是你的捕获时钟并不适合它。 e.getMessage()将获取消息但不打印它。

我建议使用 e.printStackTrace()(对于生产系统,您希望在例外情况下做更有用的事情)。