2012-03-07 125 views
4

我想鎖定特定文件夾,和我有代碼,但「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) { } 
     } 

    } 
} 

任何一個可以解決這一問題

+4

如果最後沒有catch(Exception e){}',我會更加認真地對待它。 – skaffman 2012-03-07 09:45:27

+0

mani1是一個文件嗎? 如果是,您是否有寫入權限? 確切的堆棧跟蹤將是有用的... 要回答最後一個問題,我會建議打印一些關於電子郵件的信息... – 2012-03-07 09:47:37

回答

0

嘗試,因爲在C-UR運行你的文件夾throught管理員或首次運行IDE作爲管理和運行文件 :/系統訪問權限需要

2

您需要添加一個異常處理程序來處理例外。在

File file = new File("C:\\Users\\kaizen\\Desktop\\mani1.addExtension"); 

這將解決您的問題。

+1

添加擴展不會解決用戶的問題。用戶正在嘗試設置目錄級別的鎖用他寫的代碼是不可能的。用戶試圖獲得可能的dir並因此失敗。 – xyz 2015-06-24 16:41:05