Sample Programs

Sample java program to check and change file attribute from read-only to writable

 package org.jusfortechies.example; 

 import java.io.File;
 import java.io.IOException;

 public class ChangeFileAttribute {

   public static void main(String[] args) {
      
      try {
         File file = new File("C:\\samplefile.txt");

         file.createNewFile();

         // First set the file attribute to read only (- this is for testing)
         file.setReadOnly();

         // Check whether the file content can be modified.
         if (file.canWrite()) {
            System.out.println("File is writable");
         } else {
            System.out.println("File is read-only");
         }

         // Make file writable
         file.setWritable(true);

         // Check again whether the file content can be modified.
         if (file.canWrite()) {
            System.out.println("File is writable");
         } else {
            System.out.println("File is read-only");
         }

      } catch (IOException ie) {
         System.err.println("Cannot perform IO operation : " + ie);
      }
      
   }

 }




blog comments powered by Disqus