Getting and setting all attributes for a file in Java

Abstract: Demonstrates using java.nio.file.Files to read and write BasicFileAttributes and DosFileAttributes for file metadata management.

Created: 2026-08-22 by
You can get and set file attributes in Java by using the java.nio.file.Files class with its readAttributes and writeAttributes methods. This approach relies on the BasicFileAttributes interface for standard metadata like creation time and size, while specialized interfaces handle Windows-specific flags such as hidden or system status.

Understanding File Attributes in Java NIO

The java.nio.file package provides a robust API for file manipulation introduced in Java 7. Instead of relying on older java.io.File methods which are limited, the NIO.2 API allows you to interact with the underlying file system provider. When working on Windows, you will primarily deal with two types of attributes: basic POSIX-like attributes and extended Windows-specific attributes.

For general purposes, BasicFileAttributes covers most needs, including existence, directory status, regular file status, link status, size, and timestamps. However, if you need to manipulate visibility or system-level flags, you must use the DosFileAttributes interface, which is specific to Windows environments. This distinction is crucial because attempting to cast basic attributes to DOS attributes will result in a runtime exception.

Reading File Attributes

To retrieve attributes, you first need a Path object representing your target file. You then call the static method Files.readAttributes(), passing the path and the specific attribute class you wish to read. For example, reading basic attributes returns an object containing data about the file's physical properties.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;

public class AttributeReader {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("C:\\example\\file.txt");
        
        // Read Basic Attributes
        BasicFileAttributes basicAttrs = Files.readAttributes(path, BasicFileAttributes.class);
        System.out.println("Is Regular File: " + basicAttrs.isRegularFile());
        System.out.println("Size (bytes): " + basicAttrs.size());
        System.out.println("Creation Time: " + basicAttrs.creationTime());
        
        // Read DOS (Windows) Specific Attributes
        DosFileAttributes dosAttrs = Files.readAttributes(path, DosFileAttributes.class);
        System.out.println("Is Hidden: " + dosAttrs.isHidden());
        System.out.println("Is System: " + dosAttrs.isSystem());
    }
}

This code demonstrates how to extract both standard metadata and Windows-specific flags. Note that DosFileAttributes inherits from BasicFileAttributes, so you can access basic info through the DOS interface as well. If the file does not exist, these calls will throw a FileNotFoundException.

Setting File Attributes

Modifying attributes requires the Files.setAttribute() method. This method takes the path, the attribute name in dot-notation, and the new value. The attribute names follow a specific convention defined by the file system provider. For DOS attributes, the prefix is typically dos:.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class AttributeSetter {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("C:\\example\\file.txt");
        
        // Set Hidden Attribute
        Files.setAttribute(path, "dos:hidden", true);
        
        // Set System Attribute
        Files.setAttribute(path, "dos:system", true);
        
        // Verify changes
        DosFileAttributes attrs = Files.readAttributes(path, DosFileAttributes.class);
        System.out.println("New Hidden Status: " + attrs.isHidden());
    }
}

When setting attributes, ensure the user running the Java process has sufficient permissions. On Windows, modifying system attributes often requires administrator privileges. If you attempt to set an unsupported attribute or lack permission, an UnsupportedOperationException or AccessDeniedException will be thrown. For more details on setting system attributes specifically, you might find How to Set System Attribute for a File in Windows helpful for understanding OS-level constraints.

Handling Timestamps

You can also modify timestamps using the same setAttribute mechanism. The attribute names for times are lastModifiedTime, creationTime, and lastAccessTime. These require a FileTime object as the value.

import java.nio.file.Files;
import java.nio.file.attribute.FileTime;
import java.time.Instant;

// Update last modified time to now
Files.setAttribute(path, "lastModifiedTime", FileTime.from(Instant.now()));

Error Handling and Best Practices

Always wrap file operations in try-catch blocks or declare them with throws clauses. Common exceptions include IOException for general I/O errors, SecurityException for permission issues, and IllegalArgumentException for invalid attribute names. It is good practice to verify the file exists before attempting to read or write attributes to avoid unnecessary stack traces.

Additionally, be aware that some attributes may be immutable depending on the file system type (e.g., NTFS vs. FAT32) or the state of the file. For instance, you cannot change the creation time of a file on all file systems, though NTFS generally supports it. Always test your code against the specific file systems your application targets.

Frequently Asked Questions

Can I use this method on Linux or macOS?

No, the DosFileAttributes interface is specific to Windows. On Unix-like systems, you should use PosixFileAttributes to manage permissions and ownership. Attempting to read DOS attributes on Linux will throw an UnsupportedOperationException.

Why do I get an AccessDeniedException when setting attributes?

This usually occurs because the Java process lacks the necessary administrative privileges required to modify system or hidden flags. Running your application as an administrator or ensuring the file is not locked by another process can resolve this issue.

How do I check if a file is a symbolic link?

You can use Files.readAttributes(path, BasicFileAttributes.class).isSymbolicLink(). This returns true if the path points to a symlink rather than a regular file or directory.

Is there a way to copy attributes from one file to another?

Yes, you can use Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES). This option ensures that metadata like timestamps and permissions are transferred along with the file content.

What happens if I set an attribute that doesn't exist?

The setAttribute method will throw an IllegalArgumentException. Ensure you use the correct attribute name format, such as dos:hidden for Windows-specific flags, to avoid this error.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More