How can I change a file attribute to writable?
Category: java.io, viewed: 1691 time(s).
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. But now in 1.6 a new method named setWritable() was introduced to do exactly what the method name says.
package org.kodejava.example.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. file.createNewFile(); // Set file attribute to read only so that it cannot be written 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 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!"); } } } |
The result of the program below tell us that we can change the file attribute easily.
File is in read only mode! File is writable!
Related Examples
- How do I store properties as XML file?
- How do I load properties from XML file?
- How do I convert InputStream to String?
- How do I convert string into InputStream?
- How do I get an exception stack trace message?
- How do I use Console class to read user input?
- How do I store objects in file?
- How do I use DataInputStream and DataOutputStream?
- How do I use RandomAccessFile class?
- How do I create a directories recursively?
|
|