This code demonstrate how we can modify file attribute to be read only. File
class has a setReadOnly()
method to make file read only and a canWrite()
method to know whether it is writable or not.
package org.kodejava.io;
import java.io.File;
public class FileReadOnlyExample {
public static void main(String[] args) throws Exception {
File file = new File("ReadOnly.txt");
// Create a file only if it doesn't exist.
boolean created = file.createNewFile();
// Set file attribute to read only so that it cannot be written
boolean succeeded = file.setReadOnly();
// We are using the canWrite() method to check whether we can
// modified file content.
if (file.canWrite()) {
System.out.println("File is writable!");
} else {
System.out.println("File is in read only mode!");
}
}
}
This code snippet print the following output:
File is in read only mode!
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024