- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to make a file read-only in Java
Problem Description
How to make a file read-only?
Solution
This example demonstrates how to make a file read-only by using file.setReadOnly() and file.canWrite() methods of File class.
import java.io.File; public class Main { public static void main(String[] args) { File file = new File("C:/java.txt"); System.out.println(file.setReadOnly()); System.out.println(file.canWrite()); } }
Result
The above code sample will produce the following result.To test the example,first create a file 'java.txt' in 'C' drive.
true false
The following is another sample example of file read-only in java
import java.io.File; import java.io.IOException; public class FileReadAttribute { public static void main(String[] args) throws IOException { File file = new File("c:/file.txt"); file.setReadOnly(); if(file.canWrite()) { System.out.println("This file is writable"); } else { System.out.println("This file is read only"); } file.setWritable(true); if(file.canWrite()) { System.out.println("This file is writable"); } else { System.out.println("This file is read only"); } } }
The above code sample will produce the following result.To test the example,first create a file 'java.txt' in 'C' drive.
This file is read only This file is read only
java_files.htm
Advertisements