Open In App

How to Create a File with a Specific File Attribute in Java?

In Java, you can create a file with specific File attributes such as read-only, hidden, or system attributes. This allows you to control the behavior and visibility of the file in the File system. In this article, we’ll explore how to create a file with specific attributes in Java.

In this article, we will learn to create a file with a specific file attribute in Java.



Syntax:

To create a file with specific attributes in Java, we’ll use the java.nio.file.Files class specifically the setAttribute() method.

Files.setAttribute(Path path, String attribute, Object value, LinkOption... options)

Program To Create a File with a Specific File Attribute in Java

Here’s how you can create a file with a read-only attribute in Java:






// Java Program To Create a
// File with a Specific File Attribute
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
  
// Driver Class
public class GFG {
      // Main Function
    public static void main(String[] args) {
        // Specify the file path
        Path filePath = Paths.get("example.txt");
          
          try {
            // Create the file
            Files.createFile(filePath);
            // Set the read-only attribute
            Files.setAttribute(filePath, "dos:readonly", true);
            
            System.out.println("The File created with read-only attribute.");
        
          catch (IOException e) {
            System.err.println("Error creating file: " + e.getMessage());
        }
    }
}

Output :

The File created with read-only attribute.

Explanation of the above Program:

Article Tags :