Java File canWrite() method with examples

April 28, 2020 No comments Java IO File Examples canWrite

1. Introduction

The canWrite() method from Java IO API tests whether the app can have write permission to the specified path.

2. Method signature

public boolean canWrite()

Parameters:

  • method does not take any parameter

Returns

  • true - the application is allowed to write to the file; false otherwise.

Throws

  • SecurityException - when we do not have access to the file

3. Examples

3.1. Check if the application can write to the file /tmp/frontbackend.txt

package com.frontbackend.java.io;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f = new File("/tmp/frontbackend.txt");
            boolean canWrite = f.canWrite();

            if (canWrite) {
                System.out.println("Application can write the file");
            } else {
                System.out.println("Application cannot write the file");

                if (!f.exists()) {
                    System.out.println(", because the file does not exist.");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The file does not exist so canWrite() method returns false. The output will be:

Application cannot write the file
, because the file does not exist.

4. Conclusion

In this article, we presented canWrite() method from Java IO. If our application needs to check if it is allowed to write to a specified file this method is the easiest way to do that. Note that the result will be also false if the file does not exist.

{{ message }}

{{ 'Comments are closed.' | trans }}