2015-02-23 874 views
31

出於某種原因,我每次嘗試使用Tomcat上的java webapp寫入我的計算機上的文件夾時都會收到java.nio.file.AccessDeniedException。此文件夾的權限設置爲完全控制我的計算機上的每個人(Windows)。有人知道我爲什麼會得到這個異常嗎?嘗試寫入文件夾時獲取「java.nio.file.AccessDeniedException」

這裏是我的代碼:

public void saveDocument(String name, String siteID, byte doc[]) { 
    try { 
     Path path = Paths.get(rootDirectory + siteID); 
     if (Files.exists(path)) { 
      System.out.println("Exists: " + path.toString()); 
      Files.write(path, doc); 
     } else { 
      System.out.println("DOesn't exist"); 
      throw new Exception("Directory for Site with ID " + siteID + "doesn't exist"); 
     } 
    } catch (FileSystemException e) { 
     System.out.println("Exception: " + e); 
     e.printStackTrace(); 
    } catch (IOException e) { 
     System.out.println("Exception: " + e); 
     e.printStackTrace(); 
    } catch (Exception e) { 
     System.out.println("Exception: " + e); 
     e.printStackTrace(); 
    } 

這裏是錯誤:

Exception: java.nio.file.AccessDeniedException: C:\safesite_documents\site1 java.nio.file.AccessDeniedException: C:\safesite_documents\site1 at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230) at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:430) at java.nio.file.Files.newOutputStream(Files.java:172) at java.nio.file.Files.write(Files.java:3092)

可能的原因:See my post on supersuser about how I can't uncheck 'Read Only' for any of my folders on windows 7. Even though all the folders aren't read only to anything but java.

+0

嘗試寫 – Prashant 2015-02-23 10:00:42

+1

不是它不適用於不同的驅動器或不同的文件夾 有一件事可能是我的電腦上的所有文件夾都標記爲「只讀」即使它們不是隻讀,當我取消標記時,他們只是在再次檢查後 – OneTwo 2015-02-23 10:06:29

+0

@OneTwo,是否有任何其他代碼正在使用相同路徑的可能性?就像您訪問過相同路徑並忘記釋放資源 – Amogh 2015-02-23 10:48:47

回答

39

好的事實證明我是做一些愚蠢的事。我沒有將新的文件名添加到路徑中。 我有「rootDirectory = 「C:\ safesite_documents」,但它應該是「rootDirectory = 「C:\ safesite_documents \ newFile.jpg」

對不起,這是一個愚蠢的錯誤一如既往

+12

不要感到孤單,我做了完全一樣的事情!感謝你的回答。 – Yster 2016-09-23 23:10:11

+2

同樣的錯誤:),謝謝 – Anarki 2017-11-13 18:27:41

相關問題