How to Create Read only file or Mark a file as Read only in Java

By How to Create Read only file or Mark a file as Read only in Java

This tutorial shows how to create a read only file or mark an existing file as read only.

Create Read Only File in Java

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 ReadOnlyFile {
    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());
        }
    }
}

Mark a file as Read only in Java

import java.io.File;
import java.io.IOException;
public class ReadOnlyFile1 {
    public static void main(String[] args) {
        try {
            // File Path
            File file = new File("foo.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());
        }
    }
}

Was this article helpful?
Donate with PayPal: https://www.paypal.com/donate

Bessy
Eric Murithi Muchenah

Life is beautiful, time is precious. Make the most out of it.