Prior to Java 1.6 the java.io.File
class doesn’t include a method to change a read only file attribute and make it writable. To do this on the old days we have to utilize or called operating system specific command. In Java 1.6 a new method named setWritable()
was introduced to do exactly what the method name says.
package org.kodejava.io;
import java.io.File;
public class WritableExample {
public static void main(String[] args) throws Exception {
File file = new File("Writable.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!");
}
// Now make our file writable
succeeded = file.setWritable(true);
// re-check the read-write status of file
if (file.canWrite()) {
System.out.println("File is writable!");
} else {
System.out.println("File is in read only mode!");
}
}
}
And here are the result of the code snippet above:
File is in read only mode!
File is writable!
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