January 4, 2021 When you access a file, you may not be able to implement the program because you do not have permission for the file. Folders also need to get permissions, so here's a quick summary.
java.io is an old API. Folder permissions are obtained with the canWtrite method and isHidden method of the java.io.File class.
import java.io.File;
public class Sample {
public static void main(String[] args) {
File file = new File("c:\\test");
if (file.canWrite()) {
System.out.println("Can write");
} else {
System.out.println("Read-only");
}
if (file.isHidden()) {
System.out.println("It's a hidden file");
} else {
System.out.println("Not a hidden file");
}
}
}
java.nio is a new API with improved functionality from Java 7. Folder permissions are obtained with the getAttribute method of the java.nio.Files class.
Sample code
import java.nio.Files;
public class Sample {
public static void main(String[] args) {
Path path = Paths.get("c:\\test");
//"True" for read-only
System.out.println(Files.getAttribute(path, "dos:readonly"));
//“True” for hidden files
System.out.println(Files.getAttribute(path, "dos:hidden"));
}
}
[Introduction to Java] How to create a folder (java.nio.file)
Recommended Posts