Share on Google+Share on Google+

Java file canWrite()

Advertisement
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!

Advertisements

Advertisement

Posted on: April 14, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.