可能重复:
Java:检查文件是否已打开
我正在制作一个摇摆实用程序,我在其中创建和使用 Apache poi 的 excel 表。如果文件在我试图访问它时已经打开,它会抛出一个异常,就像其他进程正在使用这个 excel 文件一样。所以我只想检查该excel文件是否已经打开,如果是,则关闭它。
可能重复:
Java:检查文件是否已打开
我正在制作一个摇摆实用程序,我在其中创建和使用 Apache poi 的 excel 表。如果文件在我试图访问它时已经打开,它会抛出一个异常,就像其他进程正在使用这个 excel 文件一样。所以我只想检查该excel文件是否已经打开,如果是,则关闭它。
你有没有在这个主题上做一些谷歌搜索:这是我想出的一些
我在这里复制stackoverflow上第一个问题的答案:
File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Get an exclusive lock on the whole file
FileLock lock = channel.lock();
try {
lock = channel.tryLock();
// Ok. You get the lock
} catch (OverlappingFileLockException e) {
// File is open by someone else
} finally {
lock.release();
}
希望这会有所帮助。
你有没有试过这个:
File file = new File(pathToFile);
if (file.canRead()) {
<do whatever you are doing with the file>
}