skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Sunday, October 14, 2012

Updating Permission of a file using java program on Unix Operation System

Posted by Raju Gupta at 2:00 AM – 0 comments
 
This program will help you modify the permission of a file.on Unix operating system. You need to pass the absolute path of the file and the permission(e.g. 775,700,777 etc.) you wnat to give, as the command line parameters.

import java.io.*;
import java.util.*;

/**
 ** The FilePerm class has a method updateFilePerm
 ** to assist in changing the permission of a file on Unix OS,
 ** through java program
 **/


public class FilePerm {


    /** updateFilePerm method coverts permission of file 
     *  by using chmod command which allow either of -rwx- 
     *  permission to the file. 
     *
     */
   
    public static boolean updateFilePerm(String fileName, int mode)        
            throws Exception {   
 
 String method = "updateFilePerm";
 boolean updateError = false;
 
 /** retry concept */
        int retry = 0;
 
 /** changeMod */
        String changemod = null;
 
        
 /** Runtime class object */
        Runtime rt = null;
 
        /** Process class object */
        Process proc = null;  
       
 if (null == fileName || ("").equals(fileName)) {
                throw new Exception("Source File is null:Null pointer Exception");
        }
  if (mode < 0 || mode > 777) {
                throw new Exception("Invalid Mode");
         }
 try {     
     rt= Runtime.getRuntime();
                     
     changemod = "chmod" + " " + mode + " " + fileName;
     do {         
  /** Changing the mode of the file */
  try {
      proc = rt.exec(changemod); 
      proc.waitFor();
  } catch (IOException ioex) {                     
                     throw ioex;
  }
         /** In case of abnormal termination of proecss */
  if(proc.exitValue() != 0 ){
          updateError=true;
      retry++;
  } else { 
      updateError = false;
  }
     } while (updateError && retry < 3);
 
     return updateError; 
     
            }catch(Exception ex){

            throw ex;
        }
  
    }
    
    public static void main(String[] args) {
       try {
    updateFilePerm(args[0],Integer.parseInt(args[1]));  
       } catch(Exception Ex) {
           System.out.println("Exception in giving permission to the file :"+Ex);
       }      
    } 
       
}


Labels: Java File Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger