Java examples on Java I/O
- How do I convert InputStream to String?
- How do I read a text file?
- How do I convert string into InputStream?
- How do I use DataInputStream and DataOutputStream?
- How do I create and write data into text file?
- How do I get file's last modification date?
- How do I use RandomAccessFile class?
- How do I store objects in file?
- How do I load properties from XML file?
- How do I use Console class to read user input?
- How do I store properties as XML file?
- How do I use LineNumberReader class to read file?
- How do I append data to a text file?
- How do I get an exception stack trace message?
- How do I detect non-ASCII characters in string?
- How can I get current working directory?
- How can I change a file attribute to writable?
- How do I create a directories recursively?
- How do I use Java NIO to Copy File?
- How do I check if a directory is not empty?
- How do I copy a file?
- How do I rename a file or directory?
- How do I get total space and free space of my disk?
- How do I create a new directory?
- How do I get the absolute path of a file?
- How do I get the content of a directory?
- How do I check if a file exists?
- How do I create a temporary file?
- How can I change a file attribute to read only?
- How do I determine if a pathname is a directory?
- How do I check if a file is hidden?
- How do I delete a file?
- How do I get the size of a file?
- How do I read a file into byte array?
- How do I get the list of file system root?
- How do I display file contents in hexadecimal?
- How do I get the extension of a file?
- How do I read file using FileInputStream?
How can I change a file attribute to writable?
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!