- 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
Set file attributes in Java
One of the file attribute that can be set is to make the file read-only. This can be done by using the method java.io.File.setReadOnly(). This method requires no parameters and it returns true if the file is set to read-only and false otherwise.
The java.io.File.canRead() and java.io.File.canWrite() methods are used to check whether the file can be read or written to respectively.
A program that demonstrates this is given as follows −
Example
import java.io.File; public class Demo { public static void main(String[] args) { try { File file = new File("demo1.txt"); file.createNewFile(); if (file.canRead()) System.out.println("Readable"); else System.out.println("Not Readable"); if (file.canWrite()) System.out.println("Writable"); else System.out.println("Not Writable"); file.setReadOnly(); if (file.canRead()) System.out.println("
Readable"); else System.out.println("
Not Readable"); if (file.canWrite()) System.out.println("Writable"); else System.out.println("Not Writable"); } catch(Exception e) { e.printStackTrace(); } } }
The output of the above program is as follows −
Output
Readable Writable Readable Not Writable
Advertisements