- Check File Exists and Check File Permissions in Java
- Overview
- File Exists Check
- Using Java IO
- Using Java NIO
- Directory Exists Check
- Using Java IO
- Using Java NIO
- File Permission Check
- With Java IO
- With Java NIO
- Why should I check if File or Directory Exists?
- Summary
- Get permissions file java
- How to get file attributes or permissions using Java NIO with examples
- Get permissions file java
- Constructor Summary
- Method Summary
- Methods inherited from class java.security.Permission
- Methods inherited from class java.lang.Object
- Constructor Detail
- FilePermission
- Method Detail
- implies
- equals
- hashCode
- getActions
- newPermissionCollection
Check File Exists and Check File Permissions in Java
This is a thorough guide to perform File Exists Check or Directory Exists Check and File Permissions Check using Java IO and Java NIO API.
Overview
In Java there are two ways to perform File Input Output Operations. The traditional way is to use Plain Java IO API and the the new way is to use the Java NIO API. This tutorial covers both Java IO and Java NIO ways of doing file existence check and file permissions check.
First, we will begin by understanding How to check file and folder or directory existence. Then, we will move further to understand how to check a File permissions. In the last part we will cover Why the file File existence checks are required.
File Exists Check
This section covers both the old and the new way of checking if a file exists in the given location.
Using Java IO
With Java IO File class, we can refer to any file on the disk. To check if a File exists, we can invoke exists method provided by File. Note that we are also asserting that file is not a directory.
private boolean checkIfFileExists(String location) < File file = new File(location); assert file.isFile(); return file.exists(); >
Code language: Java (java)
Using Java NIO
The Java NIO package it the latest JavaIO API introduced in Java 7. Its Files class provides a number of static methods, which are useful for general purpose FileIO operations.
Next is the same method which uses Java NIO to check existence of a File.
private boolean checkIfFileExists(String location) < Path path = Path.of(location); assert !Files.isDirectory(path); return Files.exists(path); >
Code language: Java (java)
Directory Exists Check
Java uses the term File to refer to both a file and a directory. Hence the File class instance can refer any path which can be a file or a folder. Let’s quickly see how to Check if a directory is present.
Using Java IO
Here is a legacy Java IO way of checking if a directory exits.
private boolean checkIfDirectoryExists(String location) < File directory = new File(location); assert directory.isDirectory(); return directory.exists(); >
Code language: Java (java)
Using Java NIO
Similarly, we can use Java NIO to first assert that the file is actually a directory and it exists as well.
private boolean checkIfDirectoryExists(String location) < Path path = Path.of(location); assert Files.isDirectory(path); return Files.exists(path); >
Code language: Java (java)
File Permission Check
The previous sections explained how to see if a file or directory is actually present on the given path. Now we will check if a file as correct permissions
With Java IO
As, shown in next block, we can use Java IO to check if a file is writable.
private boolean chekFileIsWritable(String location) throws IOException < File file = new File(location); assert file.isFile() && file.exists(); return file.canWrite(); >
Code language: Java (java)
We first, ensure that the file is actually a file and it exists. The method will return true, if the application has write permissions on the file.
Similarly we can check if file has read permissions.
file.canRead();
Code language: Java (java)
Or, if the file is an executable and has permissions to execute.
file.canExecute();
Code language: Java (java)
With Java NIO
Similarly, we can use Java NIO to check if a File has read permission, write permission, and/or execute permissions.
Path path = Path.of(location); Files.isReadable(path); Files.isWritable(path); Files.isExecutable(path);
Code language: Java (java)
Why should I check if File or Directory Exists?
There are two reasons that Checking If a File Exists or a Directory Exists is important.
Firstly, when we create a File instance using Java IO or NIO the instance will be created even if the provided path is invalid.
File file = new File(location);
Code language: Java (java)
Path path = Path.of(location); File file = path.toFile();
Code language: Java (java)
However, when we want to read such a file or create an InputSteram on the file, we get FileNotFoundException or NoSuchFileException depending upon the API we use.
Secondly, the existence check can be part of the systems logic. For example, the component you are writing can depend on a file created by another part of the system and want to consume the file as soon as it is created. Thus, your component can repeatedly check if the file exists and proceed as soon as it is available.
Summary
This article explained How to find if a file or a directory exists, as well as if a file or directory has got read, write and execute permissions. It covered legacy way of using plain Java IO, as well as using the new way of Java NIO API. Also, it briefly covered why the file existence check is required. For more on Java, please visit Java Tutorials.
Get permissions file java
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
How to get file attributes or permissions using Java NIO with examples
This tutorial shows how to get the file attributes for a given file in Java with examples. It uses the Path and Files classes from the Java NIO API to fetch the attribute information of a file from the underlying file system.
The file attributes which can be read for a file are whether it is readable, writable and/or executable. Using Java NIO API the file attributes can be accessed in the following 2 steps –
- An instance of java.nio.files.Path needs to be created using the actual path to the file in the file system.
- Then using java.nio.file.Files class the attributes can be read as boolean values using the following methods with the Path instance created in step 1 passed as a parameter to the method –
- FileSystem.isReadable() – checks whether file is readable
- FileSystem.isWritable() – checks whether file is writable
- FileSystem.isExecutable() – checks whether file is executable
Let us now see a Java code example showing how to retrieve the attributes of a given file, which is followed by an explanation of the code.
package com.javabrahman.corejava; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckFileAttributes < public static void main(String args[]) < Path filePath = Paths.get("C:\\JavaBrahman\\LEVEL1\\file1.txt"); //Is file readable boolean isReadable = Files.isReadable(filePath); System.out.println("Is file readable: " + isReadable); //Is file writable boolean isWritable = Files.isWritable(filePath); System.out.println("Is file writable: " + isWritable); //Is file executable boolean isExecutable = Files.isExecutable(filePath); System.out.println("Is file executable: " + isExecutable); >>
- The class CheckFileAttributes fetches the file attributes or permissions for a file named file1.txt .
- It first creates a Path instance, named filePath , using the full path of the file( «C:\\JavaBrahman\\LEVEL1\\file1.txt» ) in the file system.(The double backward slashes(‘\\’) are to escape the single backward slash(‘\’) in the String path value on the Windows file system.)
- filePath is then passed as a parameter to three attribute checking methods –
Files.isReadable() , Files.isWritable() and Files.isExecutable() . - The printed output shows that file1.txt is readable, writable, and executable, as the value returned by all three methods is true .
Get permissions file java
This class represents access to a file or directory. A FilePermission consists of a pathname and a set of actions valid for that pathname. Pathname is the pathname of the file or directory granted the specified actions. A pathname that ends in «/*» (where «/» is the file separator character, File.separatorChar ) indicates all the files and directories contained in that directory. A pathname that ends with «/-» indicates (recursively) all files and subdirectories contained in that directory. A pathname consisting of the special token «<
Constructor Summary
Method Summary
Methods inherited from class java.security.Permission
Methods inherited from class java.lang.Object
Constructor Detail
FilePermission
Creates a new FilePermission object with the specified actions. path is the pathname of a file or directory, and actions contains a comma-separated list of the desired actions granted on the file or directory. Possible actions are «read», «write», «execute», «delete», and «readlink». A pathname that ends in «/*» (where «/» is the file separator character, File.separatorChar ) indicates all the files and directories contained in that directory. A pathname that ends with «/-» indicates (recursively) all files and subdirectories contained in that directory. The special pathname «>» matches any file. A pathname consisting of a single «*» indicates all the files in the current directory, while a pathname consisting of a single «-» indicates all the files in the current directory and (recursively) all files and subdirectories contained in the current directory. A pathname containing an empty string represents an empty path.
Method Detail
implies
- p is an instanceof FilePermission,
- p‘s actions are a proper subset of this object’s actions, and
- p‘s pathname is implied by this object’s pathname. For example, «/tmp/*» implies «/tmp/foo», since «/tmp/*» encompasses all files in the «/tmp» directory, including the one named «foo».
equals
Checks two FilePermission objects for equality. Checks that obj is a FilePermission, and has the same pathname and actions as this object.
hashCode
getActions
Returns the «canonical string representation» of the actions. That is, this method always returns present actions in the following order: read, write, execute, delete, readlink. For example, if this FilePermission object allows both write and read actions, a call to getActions will return the string «read,write».
newPermissionCollection
then the implies function must take into account both the «/tmp/-» and «/tmp/scratch/foo» permissions, so the effective permission is «read,write», and implies returns true. The «implies» semantics for FilePermissions are handled properly by the PermissionCollection object returned by this newPermissionCollection method.
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.