- 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
Java Program to create a file and sets it to read-only
A file can be set to read-only 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 method java.io.File.canWrite() is used to check whether the file can be written to in Java and if not, then the file is confirmed to be read-only.
A program that demonstrates this is given as follows −
Example
import java.io.File; public class Demo { public static void main(String[] args) { boolean flag; try { File file = new File("demo1.txt"); file.createNewFile(); flag = file.setReadOnly(); System.out.println("File is read-only?: " + flag); flag = file.canWrite(); System.out.print("File is writable?: " + flag); } catch(Exception e) { e.printStackTrace(); } } }
The output of the above program is as follows −
Output
File is read-only?: true File is writable?: false
Note − The output may vary on Online Compilers.
Now let us understand the above program.
The file can be set to read-only by using the method java.io.File.setReadOnly() and its return value is printed. The method java.io.File.canWrite() is used to is confirm that the file is read-only and to do that, its return value is printed. A code snippet that demonstrates this is given as follows −
try { File file = new File("demo1.txt"); file.createNewFile(); flag = file.setReadOnly(); System.out.println("File is read-only?: " + flag); flag = file.canWrite(); System.out.print("File is writable?: " + flag); } catch(Exception e) { e.printStackTrace(); }
- Related Articles
- Create a file and change its attribute to read-only in Java
- Golang program to make a file read-only
- Change a file attribute to read only in Java
- How to create a read-only list in Java?
- Create a Read-Only Collection in Java
- How to create a file, write data into it and read data from it on iOS?
- Java Program to convert a Map to a read only map
- Java Program to convert a list to a read-only list
- Mark file or directory Read Only in Java
- Write a C program to read a data from file and display
- Java Program to Create String from Contents of a File
- How to read only the first line of a file with Python?
- How to make Java ArrayList read only?
- How to read data from one file and print to another file in Java?
- How to make a collection read only in java?
