How to set File Permission Using Java

package JavaIOExample;

import java.io.File;
import java.util.Scanner;

/*
 * Here we will learn to Check the File Permission.If
 * 1- File is Executable
 * 2- File is readable
 * 3- File is Writable
 *
 */
public class SetFilePermission {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		System.out.println("Please enter the file path");
		String filePath = scanner.next();

		File file = new File(filePath);

		/*
		 * Tests whether the application can modify the file.
		 */
		boolean boolWritable = file.canWrite();
		System.out.println("Application can modify given File?" + boolWritable);

		/*
		 * Tests whether the application can read the file.
		 */
		boolean boolReadable = file.canRead();
		System.out.println("Application can read given File? " + boolReadable);

		/*
		 * Tests whether the application can execute the file.
		 */
		boolean boolExecutable = file.canExecute();
		System.out.println("Application can execute given File? "
				+ boolExecutable);

		/*
		 * Changing the file permissions.
		 */
		if (boolWritable)
			file.setWritable(false);
		else
			file.setWritable(true);
		if (boolReadable)
			file.setReadable(false);
		else
			file.setReadable(true);
		if (boolExecutable)
			file.setExecutable(false);
		else
			file.setExecutable(true);

		System.out.println("Changed Permission of File");
		System.out.println("Application can modify given File?"
				+ file.canWrite());
		System.out
				.println("Application can read given File? " + file.canRead());
		System.out.println("Application can execute given File? "
				+ file.canExecute());
	}
}

 

By | 2017-07-24T12:31:35+00:00 October 20th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment