Java file canWrite()


 

Java file canWrite()

This section illustrates you the use of canWrite() method.

This section illustrates you the use of canWrite() method.

Java file canWrite()

This section illustrates you the use of canWrite() method.

Description of code:

This method tests whether the file can be modified or not. So to test this, we have set the file attribute to read only mode by using the method setReadOnly(). Then we have used the method canWrite() to check whether we can modified the file content or not. This method returns boolean value. 

setReadOnly(): This method of File class marks the file or directory so that only read operations are allowed.

canWrite(): This method of File class  tests whether the file can be modified.

Here is the code:

import java.io.File;

public class FileCanWrite {
	public static void main(String[] args) throws Exception {
		File file = new File("C:/hello.txt");
		file.createNewFile();
		file.setReadOnly();
		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!

Ads