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)
- path: The path of the file.
- attribute: The attribute to set (e.g. “dos: read-only” for the read-only attribute).
- value: The attribute’s value (e.g. true for setting the read-only attribute).
- options: Optional link 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
// 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:
- We specify the file path using Paths.get() method.
- Inside the try-catch block and we create the file using the Files.createFile().
- We then set the read-only attribute using the Files.setAttribute() with attribute name “dos:readonly” and value true.
- If any exception occurs during the file creation or attribute setting and we catch and handle it appropriately.
Contact Us