Home Tutorial Java Core Files How to check if a file is read-only in java

 
 

Share on Google+Share on Google+
How to check if a file is read-only in java
Posted on: April 3, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to check if a file is read-only in java.

How to check if a file is read-only in java

A read-only file is any file with the read-only attribute. Read-only files can be opened and accessed but you will not be able to make changes to it. You can make a file read-only by using setReadOnly() method and can check this using canWrite() method of File class. If the value return from the canWrite() method is false, means that file is in read only mode and you cannot modify it.

Here is the code:

import java.io.File;

public class CheckReadOnlyMode {
  public static void main(String[] args) {
    File file = new File("c:/file.txt");
    file.setReadOnly();
    boolean b = file.canWrite();
    if (b == false) {
      System.out.println("File is in read only mode");
    else {
      System.out.println("You can write into the file");
    }
  }
}

 

Code to check read only file:

Java API provides the functions to find if any file is read only.

The boolean b = file.canWrite(); function is used.

I returns true if file is not ready only else returns false.

Advertisement

Related Tags for How to check if a file is read-only in java:


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.

Posted on: April 3, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com