VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-create-a-file-with-a-specific-file-attribute-in-java/

⇱ How to Create a File with a Specific File Attribute in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Feb, 2024

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:

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.
Comment