
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.........
Advertisements