For some reason I keep getting java.nio.file.AccessDeniedException
every time I try to write to a folder on my computer using a java webapp on Tomcat. This folder has permissions set to full control for everyone on my computer (Windows). Does anybody know why I get this exception?
Here’s my code:
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();
}
And here is the error:
Exception: java.nio.file.AccessDeniedException: C:safesite_documentssite1
java.nio.file.AccessDeniedException: C:safesite_documentssite1
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)
Possible reason why: 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.
asked Feb 23, 2015 at 9:32
5
Ok it turns out I was doing something stupid. I hadn’t appended the new file name to the path.
I had
rootDirectory = "C:\safesite_documents"
but it should have been
rootDirectory = "C:\safesite_documents\newFile.jpg"
Sorry it was a stupid mistake as always.
Ahmed Ashour
4,87810 gold badges36 silver badges52 bronze badges
answered Feb 23, 2015 at 12:01
OneTwoOneTwo
2,1096 gold badges31 silver badges51 bronze badges
4
Getting
java.nio.file.AccessDeniedException
when trying to write to a folder
Unobviously, Comodo antivirus has an «Auto-Containment» setting that can cause this exact error as well. (e.g. the user can write to a location, but the java.exe
and javaw.exe
processes cannot).
In this edge-case scenario, adding an exception for the process and/or folder should help.
Temporarily disabling the antivirus feature will help understand if Comodo AV is the culprit.
I post this not because I use or prefer Comodo, but because it’s a tremendously unobvious symptom to an otherwise functioning Java application and can cost many hours of troubleshooting file permissions that are sane and correct, but being blocked by a 3rd-party application.
answered Dec 11, 2020 at 18:08
tresftresf
6,5545 gold badges38 silver badges97 bronze badges
I was getting the same error when trying to copy a file. Closing a channel associated with the target file solved the problem.
Path destFile = Paths.get("dest file");
SeekableByteChannel destFileChannel = Files.newByteChannel(destFile);
//...
destFileChannel.close(); //removing this will throw java.nio.file.AccessDeniedException:
Files.copy(Paths.get("source file"), destFile);
answered Aug 27, 2018 at 12:11
ekeneekene
736 bronze badges
Not the answer for this question
I got this exception when trying to delete a folder where i deleted the file inside.
Example:
createFolder("folder");
createFile("folder/file");
deleteFile("folder/file");
deleteFolder("folder"); // error here
While deleteFile("folder/file");
returned that it was deleted, the folder will only be considered empty after the program restart.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#delete-java.nio.file.Path-
Explanation from dhke
answered Mar 16, 2019 at 15:22
thiagola92thiagola92
4947 silver badges10 bronze badges
After long time to open my android project (Android Studio), and it getting same issue like above.
And I solve it by «Clean Project». You Just go to menu «Build» > «Clean Project».
Dharman♦
29.3k21 gold badges80 silver badges131 bronze badges
answered Feb 26, 2022 at 1:16
Tomero IndonesiaTomero Indonesia
1,6751 gold badge15 silver badges17 bronze badges
Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.
answered Aug 13, 2019 at 6:08
vinodvinod
1,09615 silver badges18 bronze badges
I was seeing this error in my spring-boot(version : 2.6.2) project.
When I changed the version to 2.7.2 and re-built the project, the error went away.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
answered Oct 10, 2022 at 11:29
mnagdevmnagdev
2342 silver badges9 bronze badges
For some reason I keep getting java.nio.file.AccessDeniedException
every time I try to write to a folder on my computer using a java webapp on Tomcat. This folder has permissions set to full control for everyone on my computer (Windows). Does anybody know why I get this exception?
Here’s my code:
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();
}
And here is the error:
Exception: java.nio.file.AccessDeniedException: C:safesite_documentssite1
java.nio.file.AccessDeniedException: C:safesite_documentssite1
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)
Possible reason why: 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.
asked Feb 23, 2015 at 9:32
5
Ok it turns out I was doing something stupid. I hadn’t appended the new file name to the path.
I had
rootDirectory = "C:\safesite_documents"
but it should have been
rootDirectory = "C:\safesite_documents\newFile.jpg"
Sorry it was a stupid mistake as always.
Ahmed Ashour
4,87810 gold badges36 silver badges52 bronze badges
answered Feb 23, 2015 at 12:01
OneTwoOneTwo
2,1096 gold badges31 silver badges51 bronze badges
4
Getting
java.nio.file.AccessDeniedException
when trying to write to a folder
Unobviously, Comodo antivirus has an «Auto-Containment» setting that can cause this exact error as well. (e.g. the user can write to a location, but the java.exe
and javaw.exe
processes cannot).
In this edge-case scenario, adding an exception for the process and/or folder should help.
Temporarily disabling the antivirus feature will help understand if Comodo AV is the culprit.
I post this not because I use or prefer Comodo, but because it’s a tremendously unobvious symptom to an otherwise functioning Java application and can cost many hours of troubleshooting file permissions that are sane and correct, but being blocked by a 3rd-party application.
answered Dec 11, 2020 at 18:08
tresftresf
6,5545 gold badges38 silver badges97 bronze badges
I was getting the same error when trying to copy a file. Closing a channel associated with the target file solved the problem.
Path destFile = Paths.get("dest file");
SeekableByteChannel destFileChannel = Files.newByteChannel(destFile);
//...
destFileChannel.close(); //removing this will throw java.nio.file.AccessDeniedException:
Files.copy(Paths.get("source file"), destFile);
answered Aug 27, 2018 at 12:11
ekeneekene
736 bronze badges
Not the answer for this question
I got this exception when trying to delete a folder where i deleted the file inside.
Example:
createFolder("folder");
createFile("folder/file");
deleteFile("folder/file");
deleteFolder("folder"); // error here
While deleteFile("folder/file");
returned that it was deleted, the folder will only be considered empty after the program restart.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#delete-java.nio.file.Path-
Explanation from dhke
answered Mar 16, 2019 at 15:22
thiagola92thiagola92
4947 silver badges10 bronze badges
After long time to open my android project (Android Studio), and it getting same issue like above.
And I solve it by «Clean Project». You Just go to menu «Build» > «Clean Project».
Dharman♦
29.3k21 gold badges80 silver badges131 bronze badges
answered Feb 26, 2022 at 1:16
Tomero IndonesiaTomero Indonesia
1,6751 gold badge15 silver badges17 bronze badges
Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.
answered Aug 13, 2019 at 6:08
vinodvinod
1,09615 silver badges18 bronze badges
I was seeing this error in my spring-boot(version : 2.6.2) project.
When I changed the version to 2.7.2 and re-built the project, the error went away.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
answered Oct 10, 2022 at 11:29
mnagdevmnagdev
2342 silver badges9 bronze badges
Definition of Java nio file AccessDeniedException
Java nio file accessdeniedexception is thrown when the file system denied the operation, it is due to the access check or permission issue on file. The java nio file exception is a very common issue, this exception also occurs when the file directory will not contain the appropriate privilege of users. We can also use AccessDeniedException class to check if the exception is thrown due to the file permission issue.
Overview of Java nio file AccessDeniedException
In java, the nio file access denied exception is thrown when the file system denied the operation to view or edit the file. To solve this error, we need to check the permission of the file. Those exceptions are not related to the security exception or access controlled exception, which is thrown to access security managers or controllers at the time file access was denied.
The nio file package uses static methods to operate on the directories and files. To use the java nio file we have required permission on it. Like we need to check the file will contain read permission before read any contents from the file, if we need to write into the file then we need to check file contains write permission before anything is written into the file.
Key Takeaways
- To handle the java nio file access exception we use the class of AccessDeniedException. This class is useful to handle the exception of the java nio file.
- We use multiple methods and constructors to throw the exception of java nio access denied, we can also check the delegate API.
Java nio file AccessDeniedException – File System
The java nio file access denied exception occurs due to the file system. If the file does not contain appropriate permission, then it shows the access denied exception. The below example shows how file access denied exception occurs due to the file system. Below we need to import the class of AccessDeniedException. Also, we need to import the Path, Files, and Paths packages as follows.
Code:
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class java_niofile {
public static void main(String[] args) throws IOException {
Path f = Paths.get ("C:\Program Files\Java\jdk1.8.0_351\jmc.txt");
String um = "";
um = strategyA (f);
System.out.println ("Strategy A: " + um);
um = strategyB(f);
System.out.println ("Strategy B: " + um);
}
public static String strategyA(Path f) throws IOException {
String um = "";
boolean iw = Files.isWritable (f);
if (iw) {
Files.delete (f);
um = "Deleted";
} else {
um = "…..";
}
return um;
}
public static String strategyB (Path f) throws IOException {
String um = "";
try {
Files.delete(f);
um = "Deleted";
} catch (AccessDeniedException ade) {
ade.printStackTrace ();
um = ade.getMessage () + " This file is not writable.";
}
return um;
}
}
In the above example, we can see that the code throws the exception due to we have not to access the file. But in the below example, we can see that we have used the same code, and used different files. In the below example, our execution is successful. The file is successfully deleted. Also, a message shows that no such file exception.
Code:
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class java_niofile {
public static void main(String[] args) throws IOException {
Path f = Paths.get ("G:\ file.txt");
String um = "";
um = strategyA (f);
System.out.println ("Strategy A: " + um);
um = strategyB(f);
System.out.println ("Strategy B: " + um);
}
public static String strategyA(Path f) throws IOException {
String um = "";
boolean iw = Files.isWritable(f);
if (iw) {
Files.delete (f);
um = "Deleted";
} else {
um = "….";
}
return um;
}
public static String strategyB(Path f) throws IOException {
String um = "";
try {
Files.delete(f);
um = "Deleted";
} catch (AccessDeniedException ade) {
ade.printStackTrace();
um = ade.getMessage() + " This file is not writable.";
}
return um;
}
}
Error and Solution
The java nio file access denied exception error occurs because we do not have permission to access the specified file. The most common cause of the access denied error is that we have not specified privileges on that file. To check the permission of the file we can execute the below code as follows.
Code:
package java_niofile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class java_niofile {
public static void main(String[] args) {
Path f = Paths.get("C:\Program Files\Java\jdk1.8.0_351\jmc.txt");
boolean irf = Files.isRegularFile(f);
boolean ih = Files.isReadable(f);
boolean ir = Files.isReadable(f);
boolean ie = Files.isExecutable(f);
boolean isl = Files.isSymbolicLink (f);
Path dir = Paths.get ("C:\Program Files\Java\jdk1.8.0_351\");
boolean id = Files.isDirectory (dir);
boolean iw = Files.isWritable(dir);
}
}
The below example shows the AccessDeniedException error as follows. In below example file does not contain the appropriate permission so it gives the error of access denied as follows.
Code:
package java_niofile;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class java_niofile {
public static void main(String[] args) throws IOException {
Path f = Paths.get("C:\Program Files\Java\jdk1.8.0_351\jmc.txt");
String um = "";
um = stA(f);
System.out.println("Strategy B: " + um);
}
public static String stA(Path f) throws IOException {
String um = "";
try {
Files.delete(f);
um = "Deleted";
} catch (AccessDeniedException ade) {
ade.printStackTrace();
um = ade.getMessage() + " This file is not writable.";
}
return um;
}
}
The solution to the java nio file access denied exception error is to use the file that contains appropriate access and privileges. The below example shows the solution to the access denied exception error.
Code:
package java_niofile;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class java_niofile {
public static void main(String[] args) throws IOException {
Path f = Paths.get("G:\file1.txt");
String um = "";
um = stA(f);
System.out.println("Strategy B: " + um);
}
public static String stA(Path f) throws IOException {
String um = "";
try {
Files.delete(f);
um = "Deleted";
} catch (AccessDeniedException ade) {
ade.printStackTrace();
um = ade.getMessage() + " This file is not writable.";
}
return um;
}
}
Delayed File Deletion on Windows
We can experience the issue of delayed file deletion on windows. This exception is now thrown due to the illegal access of the file, but it was thrown due to the lock on to the specified file. If someone uses the same file and same time we attempt to delete this file, then windows OS locks that specified file and we have received the exception of delayed deletion of the file.
The steps of delayed file deletion on windows are as follows:
1. In the first step we need to submit the request to delete the lock file.
2. The control is returned from the method of actual file deletion that was delayed from windows.
3. At the time when the lock file is removed, another process of java for trying to create the exception of access denied.
Code:
package java_niofile;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class java_niofile {
public static void main(String[] args) throws IOException
{
new java_niofile().execute();
}
public void execute() throws IOException{
File d = new File("G:\file\test");
d.mkdirs();
char[] data = new char[100];
Arrays.fill(data, (char)'q');
for(int x = 0; x < 1760; x++)
{
File f = new File(d, "G:\file" + x);
f.createNewFile();
FileWriter fw = null;
try{
fw = new FileWriter(f);
fw.write(data);
}finally{
if(fw != null){
fw.close();
}
}
}
delete(d);
d.mkdirs();
new File(d, "f").createNewFile();
}
private void delete (File f){
if(f.isDirectory()){
for(File afile : f.listFiles())
{
delete(afile);
}
f.delete();
}else{
f.delete();
}
}
}
During IO.createDirectory
In Java, we use the mkdir function to create a new data directory. This method of java is used to take the parameter abstract path name and also defined the same into the file class of java. The mkdir function returns true if the directory is created without any error. If any error has occurred during directory creation, then it will return false in output. The java.io file class is used to create a new directory in java.
The below example shows to create the directory in java as follows:
Code:
package java_niofile;
import java.io.*;
class java_niofile {
public static void main(String[] args)
{
File f = new File("G:\file");
if (f.mkdir() == true) {
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
}
}
Conclusion
The java nio file access denied exception is a very common issue, this exception also occurs when the file directory will not contain the appropriate privilege of users. The nio file package uses static methods to operate on the directories and files. To use the java nio file we have required permission on it.
Recommended Articles
This is a guide to Java nio file AccessDeniedException. Here we discuss the introduction, file system, error and solution, and delayed file deletion on windows. You can also look at the following articles to learn more –
- Java Projects Resume
- Java Garbage Collectors Types
- Java Projects for Final Year
- Java HTTP Client
This issue is now fixed in 0.14.6 release. All test-cases are passing on Windows 10. Please try re-running your code.
@Ectras you can now run your code without disabling mmap config.
Map<Integer, Integer, Void> map = MapConfig .functionsOff(Paths.get("data"), intSerializer(), intSerializer()) .get(); map.put(42, 42); System.out.println(map.get(42).get());
As mentioned before, the problem was that Windows does not allow deleting memory-mapped files unless the file’s in-memory MappedByteBuffer
is cleared.
Solution
We now have a boolean cleanBeforeDelete
flag in MMAP
(memory-mapped) configuration. If cleanBeforeDelete
is true
then as the name says, memory-mapped files get cleaned before they are deleted which gets rid of the AccessDeniedException
.
You don’t really have to learn these configurations at all because the default instances are already pre-configured and I will document these configurations on the website in detail but here is a basic overview if you are interested.
deleteAfterClean
In the following snippets deleteAfterClean
is enabled if the operating system is Windows.
val mmap = MMAP.Enabled( deleteAfterClean = OperatingSystem.isWindows, //deleteAfterClean if OS is Windows forceSave = ForceSave.Disabled //disable ForceSave )
Java code looks like
MMAP.Enabled enabled = MMAP.enabled( OperatingSystem.isWindows(), ForceSave.disabled() );
ForceSave
ForceSave
is a new configuration (#251). On Windows calling force
on MappedByteBuffer
is slower in certain situations (specially when copying memory-mapped) so this configuration was required. We can also disable force
if we just want high performance and do not care about write guarantees on fatal machine crashes.
What is force?
force
is just a function on MappedByteBuffer
that «Forces any changes made to this buffer’s content to be written to the storage device containing the mapped file — JavaDoc».
We can configure force
to tell SwayDB when it should be invoked on files in any of the following 3 cases or we can disable it.
//tells SwayDB to invoke forceSave before closing a file val beforeClose = ForceSave.BeforeClose( enableBeforeCopy = true, //also enable before copying a file enableForReadOnlyMode = false, //do not force save if the file is in read-only mode logBenchmark = true //log out time take to execute force ) //tells SwayDB to invoke forceSave before cleaning a memory-mapped file's MappedByteBuffer val beforeClean = ForceSave.BeforeClean( enableBeforeCopy = true, enableForReadOnlyMode = true, logBenchmark = true ) //tells SwayDB to invoke forceSave before copying a file. This occurs during compaction //where a file can simply be copied into another level without merge when there are no overlapping keys. val beforeCopy = ForceSave.BeforeCopy( enableForReadOnlyMode = true, logBenchmark = true ) //disables force save. val disabled = ForceSave.Disabled
Last modified on May 25th, 2015 by Joe.
This tutorial is part of Java NIO tutorial series. In this tutorial, let us get introduced to Files
class from java.nio.file
package, it offers static methods to operate on files and directories. Let us start our Java files tutorial with permissions. How to check a file if it has a certain permission before operating on it. Like check if a file has a read permission before reading it or a directory has a write permission before writing on it. Before going into how to check permissions, lets think about should we really do it? Or is this the right approach? My opinion is no, we should not check before we use it. Are you aware of TOCTTOU (pronounced ‘Tock too’).
TOCTTOU is short form for “Time to Check to Time of Use”. We do a permission check and then based on result we perform operation on the respective object. What will happen if the permission is changed in between? This might lead to security holes as our logic is based on this race condition. A possible solution to this scenario is to design our application logic to directly perform the action and if it is allowed let the operation complete and if not let us have a fallback. So eventually going to exception handling mechanism based programming.
Is Readable, Hidden, Writable, Executable?
Now let us learn about how to check file permissions. Be aware of TOCTTOU and use the below accordingly. I suggest an alternate approach below instead of checking for permissions and acting based on it.
package com.javapapers.java.nio; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FilePermissionNIO { public static void main(String args[]) { Path file = Paths.get("C:\Users\Cycle\Desktop\a.html"); boolean isRegularFile = Files.isRegularFile(file); boolean isHidden = Files.isReadable(file); boolean isReadable = Files.isReadable(file); boolean isExecutable = Files.isExecutable(file); boolean isSymbolicLink = Files.isSymbolicLink(file); Path directory = Paths.get("C:\Users\Cycle\Desktop"); boolean isDirectory = Files.isDirectory(directory); boolean isWritable = Files.isWritable(directory); } }
Nice thing about these methods by default can identify symbolic links and trace to the real file and check for permission. It provides argument if it is not required to do so.
Exceptions Thrown
These methods are actually convenience methods. This delegates to some other APIs and eventually to native file system calls. AccessDeniedException
is checked exception and a type of IOException. It is thrown when a file system operation is denied due to insufficient permissions. AccessControlException
is a RuntimeException
and it is thrown by the SecurityManager when a security policy is restricting the required operation on the file.
Path file = Paths.get("C:\Users\Cycle\Desktop\a.txt"); Files.delete(file);
Delete a file using the above line of code and then change the permission to read-only. Now try to delete the file and you will get the following exception on a Windows operating system and this is dependent on the native calls.
Exception in thread "main" java.nio.file.AccessDeniedException: C:UsersCycleDesktopa.txt 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.implDelete(WindowsFileSystemProvider.java:269) at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103) at java.nio.file.Files.delete(Files.java:1126) at com.javapapers.java.nio.FilePermissionNIO.main(FilePermissionNIO.java:24)
Operation based on File Permissions
People have different opinions on this. I strongly believe we should follow “strategy-B” to design our programs when encountering file permission based decision scenarios. Generally exception handling mechanism is not to be used for decision making or branching but this scenario is different.
package com.javapapers.java.nio; import java.io.IOException; import java.nio.file.AccessDeniedException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FilePermissionNIO { public static void main(String args[]) throws IOException { Path file = Paths.get("C:\Users\Cycle\Desktop\a.txt"); String userMessage = ""; userMessage = strategyA(file); System.out.println("Strategy A: " + userMessage); userMessage = strategyB(file); System.out.println("Strategy B: " + userMessage); } public static String strategyA(Path file) throws IOException { String userMessage = ""; boolean isWritable = Files.isWritable(file); if (isWritable) { Files.delete(file); userMessage = "Deleted Successfully!"; } else { userMessage = "File is not writable."; } return userMessage; } public static String strategyB(Path file) throws IOException { String userMessage = ""; try { // do not check for permission // just go ahead and delete // if denied, act based on it Files.delete(file); userMessage = "Deleted Successfully!"; } catch (AccessDeniedException ade) { ade.printStackTrace(); userMessage = ade.getMessage() + " File is not writable."; } return userMessage; } }
Please share your opinion as comments for this tutorial as it will really help.
- java.lang.Object
-
- java.lang.Throwable
-
- java.lang.Exception
-
- java.io.IOException
-
- java.nio.file.FileSystemException
-
- java.nio.file.AccessDeniedException
- All Implemented Interfaces:
Serializable
public class AccessDeniedException extends FileSystemException
Checked exception thrown when a file system operation is denied, typically due to a file permission or other access check.
This exception is not related to the AccessControlException
or SecurityException
thrown by access controllers or security managers when access to a file is denied.
- Since:
- 1.7
- See Also:
- Serialized Form
Constructor Summary
Constructor | Description |
---|---|
AccessDeniedException(String file) |
Constructs an instance of this class. |
AccessDeniedException(String file, |
Constructs an instance of this class. |
Method Summary
Methods declared in class java.nio.file.FileSystemException
getFile, getMessage, getOtherFile, getReason
Methods declared in class java.lang.Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods declared in class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Constructor Detail
AccessDeniedException
public AccessDeniedException(String file)
Constructs an instance of this class.
- Parameters:
-
file
— a string identifying the file ornull
if not known
AccessDeniedException
public AccessDeniedException(String file, String other, String reason)
Constructs an instance of this class.
- Parameters:
-
file
— a string identifying the file ornull
if not known -
other
— a string identifying the other file ornull
if not known -
reason
— a reason message with additional information ornull
© 1993, 2020, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian’s OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/AccessDeniedException.html