CodeGym /Courses /JAVA 25 SELF /Getting and changing file attributes

Getting and changing file attributes

JAVA 25 SELF
Level 39, Lesson 4
Available

1. Reading basic attributes: BasicFileAttributes

When we talk about a file or a folder, we mean not only its name or size. Each file has a “passport”—a set of attributes that includes:

  • Creation time
  • Last modified time
  • Last access time
  • Size
  • Permissions (who can read, write, execute)
  • Owner information (on Unix)
  • Flags like “hidden”, “read-only” and more

In Java, there is a convenient and powerful API in the package java.nio.file.attribute for working with these attributes. You don't need to write platform-specific code: everything you need is in the standard library.

To begin with—import the required classes:

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.IOException;

How do you get basic file attributes?

Use the Files.readAttributes method:

Path path = Paths.get("example.txt");
try {
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);

    System.out.println("Created: " + attrs.creationTime());
    System.out.println("Modified: " + attrs.lastModifiedTime());
    System.out.println("Last access: " + attrs.lastAccessTime());
    System.out.println("Size: " + attrs.size());
    System.out.println("Is it a directory? " + attrs.isDirectory());
    System.out.println("Is it a regular file? " + attrs.isRegularFile());
    System.out.println("Is it a symbolic link? " + attrs.isSymbolicLink());
} catch (IOException e) {
    System.out.println("Error reading attributes: " + e.getMessage());
}

Imagine you're an inspector who came to check an apartment. You don't just look to see whether there's a door (the file exists); you also ask the residents: “When was the building constructed? When was the last renovation? Who is the owner?”

BasicFileAttributes properties at a glance

Property What does it return?
creationTime()
Creation date and time of the file/folder
lastModifiedTime()
Last modification date and time
lastAccessTime()
Last access date and time
size()
File size (in bytes)
isDirectory()
Is it a directory?
isRegularFile()
Is it a regular file?
isSymbolicLink()
Is it a symbolic link?

2. Extended attributes: POSIX and DOS

POSIX attributes (Linux, macOS, and other Unix-like OSes)

If you're on a Unix system, you can retrieve extended information: permissions, owner, group.

try {
    PosixFileAttributes posixAttrs = Files.readAttributes(path, PosixFileAttributes.class);
    System.out.println("Owner: " + posixAttrs.owner().getName());
    System.out.println("Group: " + posixAttrs.group().getName());
    System.out.println("Permissions: " + PosixFilePermissions.toString(posixAttrs.permissions()));
} catch (UnsupportedOperationException e) {
    System.out.println("POSIX attributes are not supported on this OS.");
} catch (IOException e) {
    System.out.println("Error reading POSIX attributes: " + e.getMessage());
}

Note: On Windows, this code will throw UnsupportedOperationException—this is expected.

DOS attributes (Windows)

On Windows, you can work with the “read-only”, “hidden”, “archive”, and “system” flags:

try {
    DosFileAttributes dosAttrs = Files.readAttributes(path, DosFileAttributes.class);
    System.out.println("Hidden: " + dosAttrs.isHidden());
    System.out.println("Read-only: " + dosAttrs.isReadOnly());
    System.out.println("System: " + dosAttrs.isSystem());
    System.out.println("Archive: " + dosAttrs.isArchive());
} catch (UnsupportedOperationException e) {
    System.out.println("DOS attributes are not supported on this OS.");
} catch (IOException e) {
    System.out.println("Error reading DOS attributes: " + e.getMessage());
}

3. Modifying file attributes

Reading someone else’s passport is one thing, changing the date of birth or last name is another! In Java, we can modify file attributes (of course, with the necessary permissions).

Changing the last modification time

import java.nio.file.attribute.FileTime;

Path file = Paths.get("example.txt");
try {
    FileTime newTime = FileTime.fromMillis(System.currentTimeMillis() - 24 * 60 * 60 * 1000); // minus 1 day
    Files.setLastModifiedTime(file, newTime);
    System.out.println("Last modification time updated!");
} catch (IOException e) {
    System.out.println("Error changing time: " + e.getMessage());
}

Changing permissions (POSIX)

Unix systems only! For example, make the file executable for everyone:

try {
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-xr-x");
    Files.setPosixFilePermissions(file, perms);
    System.out.println("Permissions updated!");
} catch (UnsupportedOperationException e) {
    System.out.println("POSIX permissions are not supported on this OS.");
} catch (IOException e) {
    System.out.println("Error changing permissions: " + e.getMessage());
}

Explanation for the string "rwxr-xr-x":

  • r — read
  • w — write
  • x — execute
  • The first block of 3 characters is for the owner, the second for the group, the third for others.

Changing hidden/read-only status (DOS attributes, Windows)

Make a file hidden:

try {
    Files.setAttribute(file, "dos:hidden", true);
    System.out.println("The file is now hidden (Windows)!");
} catch (UnsupportedOperationException e) {
    System.out.println("DOS attributes are not supported on this OS.");
} catch (IOException e) {
    System.out.println("Error changing attribute: " + e.getMessage());
}

Make a file “read-only”:

try {
    Files.setAttribute(file, "dos:readonly", true);
    System.out.println("The file is now read-only (Windows)!");
} catch (UnsupportedOperationException e) {
    System.out.println("DOS attributes are not supported on this OS.");
} catch (IOException e) {
    System.out.println("Error changing attribute: " + e.getMessage());
}

4. Checking access permissions

Sometimes it's important to quickly check whether a file can be opened for reading, writing, or execution:

Path file = Paths.get("example.txt");
System.out.println("Readable: " + Files.isReadable(file));
System.out.println("Writable: " + Files.isWritable(file));
System.out.println("Executable: " + Files.isExecutable(file));

This works the same on all platforms, although the actual behavior depends on the OS and security settings.

5. Practice: print detailed information about a file

Let's write a small program that, given a file path, will show as much information as possible and try to modify some attributes.

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Set;
import java.io.IOException;

public class FileAttributesDemo {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("example.txt");

        if (!Files.exists(path)) {
            System.out.println("File not found!");
            return;
        }

        // Basic attributes
        BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
        System.out.println("Name: " + path.getFileName());
        System.out.println("Path: " + path.toAbsolutePath());
        System.out.println("Size: " + attrs.size() + " bytes");
        System.out.println("Created: " + attrs.creationTime());
        System.out.println("Modified: " + attrs.lastModifiedTime());
        System.out.println("Last access: " + attrs.lastAccessTime());
        System.out.println("Is it a directory? " + attrs.isDirectory());
        System.out.println("Is it a regular file? " + attrs.isRegularFile());

        // Access checks
        System.out.println("Readable: " + Files.isReadable(path));
        System.out.println("Writable: " + Files.isWritable(path));
        System.out.println("Executable: " + Files.isExecutable(path));

        // Try to change the modification time
        FileTime now = FileTime.fromMillis(System.currentTimeMillis());
        Files.setLastModifiedTime(path, now);
        System.out.println("Last modification time updated!");

        // Try to make the file hidden (if supported)
        try {
            Files.setAttribute(path, "dos:hidden", true);
            System.out.println("The file became hidden (if the OS supports it).");
        } catch (UnsupportedOperationException e) {
            System.out.println("Hidden files are not supported on this OS.");
        }

        // Try to print POSIX permissions (if supported)
        try {
            PosixFileAttributes posixAttrs = Files.readAttributes(path, PosixFileAttributes.class);
            System.out.println("Owner: " + posixAttrs.owner().getName());
            System.out.println("Permissions: " + PosixFilePermissions.toString(posixAttrs.permissions()));
        } catch (UnsupportedOperationException e) {
            System.out.println("POSIX attributes are not supported on this OS.");
        }
    }
}

6. Useful nuances

Cross‑platform differences and tips

  • Not all attributes are available on every OS! Windows doesn't have POSIX permissions, and Linux doesn't have DOS attributes.
  • Always use try-catch! Methods can throw UnsupportedOperationException or IOException.
  • Permissions aren't always just “rwx”! On Windows the permission model is different; “read-only” can be enforced by the OS security policy.
  • Hidden files are a relative concept. On Unix, a file is hidden if its name starts with a dot (.hidden), on Windows—if the dos:hidden attribute is set.

Table: which attributes are available where

Attribute Windows (dos:*) Linux/macOS (posix:*)
Creation time + +
Last modification time + +
Last access time + +
Hidden file + Only by name starting with a dot
Read-only + +
Permissions (rwx) - +
Owner, group - +
Archive, system + -

7. Common mistakes when working with file attributes

Error #1: Trying to read or change POSIX attributes on Windows. On Windows you'll get UnsupportedOperationException. Always handle this exception if you write cross‑platform code.

Error #2: Changing the modification time of a file that is open in another process. On some systems the file may be locked and the operation will fail.

Error #3: Expecting the “hide file” operation to work the same on every OS. On Unix, a file is hidden if it starts with a dot (.gitignore), while on Windows it's hidden if the dos:hidden attribute is set. Don't confuse these approaches.

Error #4: Skipping the file existence check before an operation. If the file doesn't exist, you'll get NoSuchFileException when you try to get or change its attributes.

Error #5: Not checking access permissions. If the user lacks permission to change attributes, the operation will fail. Check Files.isWritable(path) before making changes.

1
Task
JAVA 25 SELF, level 39, lesson 4
Locked
Security Expert: access rights audit
Security Expert: access rights audit
1
Task
JAVA 25 SELF, level 39, lesson 4
Locked
Archive Custodian: timestamp update
Archive Custodian: timestamp update
1
Survey/quiz
Working with the file system, level 39, lesson 4
Unavailable
Working with the file system
Working with the file system
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION