In this quick and simple article, you’ll learn how to create a read only file or mark an existing file as read only.
Java create Read only file
The following example demonstrates how to create a read-only file using the createFile()
method of java.nio.file.Files
class.
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
public class CreateReadOnlyFileExample {
public static void main(String[] args) {
try {
// File Path
Path filePath = Paths.get("foo.txt");
// File permissions (Read only for USER, GROUP, and OTHER)
Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("r--r--r--");
FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
// Create a file at the given file path with the given attributes
Files.createFile(filePath, fileAttributes);
System.out.println("Read only file created successfully");
} catch (FileAlreadyExistsException e) {
System.out.println("File already exists");
} catch (IOException e) {
System.out.println("An I/O error occurred: " + e.getMessage());
} catch (SecurityException e) {
System.out.println("No permission to create file: " + e.getMessage());
}
}
}
Create a Read only file or Mark a file as Read only
There is another way to create a read only file or mark an existing file as read only using the java.io.File class’s setReadOnly()
or setWritable()
methods. The following example demonstrates the usage.
Note: you should try to use the previous method because that’s extensible and gives you more control.
import java.io.File;
import java.io.IOException;
public class CreateReadOnlyFileExample1 {
public static void main(String[] args) {
try {
// File Path
File file = new File("bar.txt");
boolean isCreated = file.createNewFile();
if(isCreated) {
System.out.println("File created successfully");
boolean success = file.setReadOnly(); // or file.setWritable(false);
if(success) {
System.out.println("File marked as read only");
} else {
System.out.println("File could not be marked as read only");
}
} else {
System.out.println("File already exists");
}
} catch (IOException e) {
System.out.println("An I/O error occurred: " + e.getMessage());
} catch (SecurityException e) {
System.out.println("No permission to create file: " + e.getMessage());
}
}
}