Java file setWritable()


 

Java file setWritable()

This section demonstrates you the use of method setWritable().

This section demonstrates you the use of method setWritable().

Java file setWritable()

This section demonstrates you the use of method setWritable().

Explanation:

In the previous versions of java, the java.io.File class doesn't include a method to change a read only file attribute and make it writable. But Java 1.6 has introduced a method named setWritable() for this purpose.

In the given example, we have marked the file status to read only. After invoking this method, the file or directory is guaranteed not to change until it is either deleted or marked to allow write access. Now to make it a writable, use the  method setWritable(true). This method then make the file writable and you can modify the file content.

setReadOnly(): This method

setWritable(): This method sets the owner's or everybody's write permission.

Here is the code:

import java.io.File;

public class FileSetWritable {
	public static void main(String[] args) throws Exception {
		File file = new File("C:/data.txt");
		file.setReadOnly();
		if (file.canWrite()) {
			System.out.println("File is writable!");
		} else {
			System.out.println("File is in read only mode!");
		}
		file.setWritable(true);
		if (file.canWrite()) {
			System.out.println("File is writable!");
		} else {
			System.out.println("File is in read only mode!");
		}
	}
}

Output:

File is in read only mode!
File is writable!

Ads