Created
September 25, 2017 13:29
-
-
Save javamultiplex/678c29dc264f65624054386eb2e7a104 to your computer and use it in GitHub Desktop.
How to change file permissions in Windows using Java?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex.filehandling; | |
import java.io.File; | |
import java.util.Scanner; | |
/** | |
* | |
* @author Rohit Agarwal | |
* @category Problem Handling | |
* @problem How to set new permissions of given file in Java? | |
* | |
*/ | |
public class SetFilePermissionInWindows { | |
public static void main(String[] args) { | |
Scanner input = null; | |
try { | |
input = new Scanner(System.in); | |
System.out.println("Enter file name with extension : "); | |
String fileName = input.nextLine(); | |
if (isValidFileName(fileName)) { | |
// File is present in current working directory. | |
File file = new File(fileName); | |
if (file.exists()) { | |
System.out.println("Before changing file permissions."); | |
System.out.println("Executable : " + file.canExecute()); | |
System.out.println("Readable : " + file.canRead()); | |
System.out.println("Writable : " + file.canWrite()); | |
if (!file.canExecute()) { | |
file.setExecutable(true); | |
} | |
if (!file.canRead()) { | |
file.setReadable(true); | |
} | |
if (!file.canWrite()) { | |
file.setWritable(true); | |
} | |
System.out.println("After changing file permissions."); | |
System.out.println("Executable : " + file.canExecute()); | |
System.out.println("Readable : " + file.canRead()); | |
System.out.println("Writable : " + file.canWrite()); | |
} else { | |
System.out.println("File is not present in current directory."); | |
} | |
} else { | |
System.out.println("File name is not valid."); | |
} | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
} | |
} | |
private static boolean isValidFileName(String fileName) { | |
String pattern = "^.+\\..+$"; | |
boolean result = false; | |
if (fileName.matches(pattern)) { | |
result = true; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment