如何在Java中实现
问题描述:
我想锁定特定文件夹,和我有代码,但“java.io.FileNotFoundException:(拒绝访问)”的文件夹锁发现错误如何在Java中实现
public class Folder_Lock {
public static void main(String[] args) {
FileLock lock = null;
FileChannel channel = null;
try {
// Get a file channel for the file
File file = new File("C:\\Users\\kaizen\\Desktop\\mani1");
channel = new RandomAccessFile(file, "rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
lock = channel.lock();
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
// Release the lock
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (lock!=null) try { lock.release(); } catch (IOException e) { }
// Close the file
if (channel!=null) try { channel.close(); } catch (IOException e) { }
}
}
}
任何一个可以解决这一问题
答
尝试,因为在C-UR运行你的文件夹throught管理员或首次运行IDE作为管理和运行文件 :/系统访问权限需要
答
您需要添加一个异常处理程序来处理例外。在
File file = new File("C:\\Users\\kaizen\\Desktop\\mani1.addExtension");
这将解决您的问题。
+1
添加扩展不会解决用户的问题。用户正在尝试设置目录级别的锁用他写的代码是不可能的。用户试图获得可能的dir并因此失败。 – xyz 2015-06-24 16:41:05
如果最后没有catch(Exception e){}',我会更加认真地对待它。 – skaffman 2012-03-07 09:45:27
mani1是一个文件吗? 如果是,您是否有写入权限? 确切的堆栈跟踪将是有用的... 要回答最后一个问题,我会建议打印一些关于电子邮件的信息... – 2012-03-07 09:47:37