Java – Check if file is writable

In this tutorial, we will learn about the Java File.canWrite() function, and learn how to use this function to check the application can write to specified file, with the help of examples.

canWrite()

File.canWrite() checks whether the file is present and if the application can modify this file.

If the file is present and application can modify this file, canWrite() returns true, else it returns false.

The syntax of canWrite() function is

</>
Copy
canWrite()

Returns

The function returns boolean value.

Examples

1. Positive Scenario – The file is writable

In this example, we will take a file with path "D:\sample.txt". Since the file is present at the location and is writable by the application, canRead() returns true.

Java Program

</>
Copy
import java.io.File;

public class Example {
	public static void main(String args[]) {
		File f = new File("D:\\sample.txt");
		if (f.canWrite()) {
			System.out.println("The file is writable."); 
		}
		else {
			System.out.println("The file is not writable."); 
		}
	}
}

Output

The file is writable.

2. Negative Scenario – The file is not writable

In this example, we will try to recreate a scenario where canWrite() returns false. An easy situation would be when the file is not present.

Java Program

</>
Copy
import java.io.File;

public class Example {
	public static void main(String args[]) {
		File f = new File("D:\\sample_not_present.txt");
		if (f.canWrite()) {
			System.out.println("The file is writable."); 
		}
		else {
			System.out.println("The file is not writable."); 
		}
	}
}

Output

The file is not writable.

Conclusion

In this Java Tutorial, we have learnt the syntax of Java File.canWrite() function, and also how to use this function with the help of examples.