- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to set file permissions in Java?
In general, whenever you create a file you can restrict/permit certain users from reading/writing/executing a file.
In Java files (their abstract paths) are represented by the Files class of the java.io package. This class provides various methods to perform various operations on files such as read, write, delete, rename etc.
In addition, this class also provides the following methods −
- setExecutble() − This method is sued to set the execute permissions to the file represented by the current (File) object.
- setWritable() − This method is used to set the write permissions to the file represented by the current (File) object.
- setReadable() − This method is used to set the read permissions to the file represented by the current (File) object.
Example
Following Java program creates a file writes some data into It and set read, write and execute permission to it.
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FilePermissions { public static void main(String args[]) throws IOException { String directoryPath = "D:/SampleDirectory"; String fileName = "example.txt"; //Creating a directory new File(directoryPath).mkdir(); System.out.println("Directory created........."); //Creating a file File file = new File(directoryPath+fileName); System.out.println("File created........."); //Writing data into the file FileWriter writer = new FileWriter(file); String data = "Hello welcome to Tutorialspoint"; writer.write(data); System.out.println("Data entered........."); //Setting permissions to the file file.setReadable(true); //read file.setWritable(true); //write file.setExecutable(true); //execute System.out.println("Permissions granted........."); } }
Output
Directory created......... File created......... Data entered......... Permissions granted.........
- Related Articles
- File Permissions in java
- How to change file permissions in Python?
- File Permissions in C#
- How to Copy File Permissions and Ownership to Another File in Linux?
- Advanced File Permissions in Linux
- How to check the permissions of a file using Python?
- Set file attributes in Java
- Getting root permissions on a file inside of vi on Linux
- How to Copy NTFS permissions using PowerShell?
- How to use file class in Java?
- How to truncate a file in Java?
- How to compress a file in Java?
- How to set a value to a file input in HTML?
- How to set path in Java?
- How to create a pdf file in Java?

Advertisements