How to make a file read-only?
SolutionThis 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4