Java 创建只读文件或将文件标记为只读

x33g5p2x  于10个月前 转载在 Java  
字(2.1k)|赞(0)|评价(0)|浏览(100)

在这篇快速而简单的文章中,您将学习如何创建只读文件或将现有文件标记为只读。

Java 创建只读文件

以下示例演示如何使用 java.nio.file.Files 类的 createFile() 方法创建只读文件。

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

创建只读文件或将文件标记为只读

还有另一种方法可以使用 java.io.File 类的 setReadOnly()setWritable() 方法创建只读文件或将现有文件标记为只读。 下面的例子演示了用法。

注意: 您应该尝试使用前面的方法,因为它是可扩展的,并为您提供更多控制。

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

相关文章

热门文章

更多