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);
}
}
}