Java : File with Examples

File (Java SE 22 & JDK 22) with Examples.
You will find code examples on most File methods.

Warning :

  • The File class is a legacy API. It is recommended to use the newer APIs Path and Files instead.


Summary

An abstract representation of file and directory pathnames.

Class diagram

Note :

  • Most of the code examples in this article are run on Windows. However, some of the code examples are run on Linux.
final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

System.out.println(file.exists()); // false

try (final var writer = new FileWriter(file)) {
    writer.write("abc");
    writer.write("XYZ");
}

System.out.println(file.exists()); // true
System.out.println(file.isFile()); // true
System.out.println(file.isDirectory()); // false

// --- PowerShell ---
//PS R:\java-work> ls -Name
//aaa.txt
//
//PS R:\java-work> cat aaa.txt
//abcdXYZ

Fields

static final String pathSeparator

The system-dependent path-separator character, represented as a string for convenience.

final var os = System.getProperty("os.name");
System.out.println(os); // Windows 10

System.out.println(File.pathSeparator); // ;
System.out.println(Arrays.toString(File.pathSeparator.getBytes())); // [59]

static final char pathSeparatorChar

The system-dependent path-separator character.

final var os = System.getProperty("os.name");
System.out.println(os); // Windows 10

System.out.println(File.pathSeparatorChar); // ;

final int c = File.pathSeparatorChar;
System.out.println(c); // 59

static final String separator

The system-dependent default name-separator character, represented as a string for convenience.

final var os = System.getProperty("os.name");
System.out.println(os); // Windows 10

System.out.println(File.separator); // \
System.out.println(Arrays.toString(File.separator.getBytes())); // [92]

static final char separatorChar

The system-dependent default name-separator character.

final var os = System.getProperty("os.name");
System.out.println(os); // Windows 10

System.out.println(File.separatorChar); // \

final int c = File.separatorChar;
System.out.println(c); // 92

Constructors

File (File parent, String child)

Creates a new File instance from a parent abstract pathname and a child pathname string.

final var parent = new File("R:\\java-work");
System.out.println(parent); // R:\java-work

final var file = new File(parent, "aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

System.out.println(file.exists()); // false

System.out.println(file.createNewFile()); // true
System.out.println(file.exists()); // true

File (String pathname)

Creates a new File instance by converting the given pathname string into an abstract pathname.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

System.out.println(file.exists()); // false

System.out.println(file.createNewFile()); // true
System.out.println(file.exists()); // true

File (String parent, String child)

Creates a new File instance from a parent pathname string and a child pathname string.

final var parent = "R:\\java-work";
System.out.println(parent); // R:\java-work

final var file = new File(parent, "aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

System.out.println(file.exists()); // false

System.out.println(file.createNewFile()); // true
System.out.println(file.exists()); // true

File (URI uri)

Creates a new File instance by converting the given file: URI into an abstract pathname.

final var uri = URI.create("file:///R:/java-work/aaa.txt");
System.out.println(uri); // file:///R:/java-work/aaa.txt

final var file = new File(uri);
System.out.println(file); // R:\java-work\aaa.txt

System.out.println(file.exists()); // false

System.out.println(file.createNewFile()); // true
System.out.println(file.exists()); // true

Methods

boolean canExecute ()

Tests whether the application can execute the file denoted by this abstract pathname.

// --- Linux Terminal ---
//$ touch sample1.sh
//$ ls -l sample1.sh
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.sh

final var os = System.getProperty("os.name");
System.out.println(os); // Linux

final var file = new File("sample1.sh");
System.out.println(file); // sample1.sh

System.out.println(file.canExecute()); // false
System.out.println(file.setExecutable(true)); // true

System.out.println(file.canExecute()); // true

// --- Linux Terminal ---
//$ ls -l sample1.sh
//-rwxrw-r-- 1 xxxx xxxx 0 ... sample1.sh
// --- Linux Terminal ---
//$ touch sample2.sh
//$ ls -l sample2.sh
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample2.sh

final var file = new File("sample2.sh");
System.out.println(file); // sample2.sh

System.out.println(file.canExecute()); // false
System.out.println(file.setExecutable(true, false)); // true

System.out.println(file.canExecute()); // true

// --- Linux Terminal ---
//$ ls -l sample2.sh
//-rwxrwxr-x 1 xxxx xxxx 0 ... sample2.sh

boolean canRead ()

Tests whether the application can read the file denoted by this abstract pathname.

// --- Linux Terminal ---
//$ touch sample1.txt
//$ ls -l sample1.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.txt

final var os = System.getProperty("os.name");
System.out.println(os); // Linux

final var file = new File("sample1.txt");
System.out.println(file); // sample1.txt

System.out.println(file.canRead()); // true
System.out.println(file.setReadable(false)); // true

System.out.println(file.canRead()); // false

// --- Linux Terminal ---
//$ ls -l sample1.txt
//--w-rw-r-- 1 xxxx xxxx 0 ... sample1.txt
// --- Linux Terminal ---
//$ touch sample2.txt
//$ ls -l sample2.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample2.txt

final var file = new File("sample2.txt");
System.out.println(file); // sample2.txt

System.out.println(file.canRead()); // true
System.out.println(file.setReadable(false, false)); // true

System.out.println(file.canRead()); // false

// --- Linux Terminal ---
//$ ls -l sample2.txt
//--w--w---- 1 xxxx xxxx 0 ... sample2.txt

boolean canWrite ()

Tests whether the application can modify the file denoted by this abstract pathname.

// --- Linux Terminal ---
//$ touch sample1.txt
//$ ls -l sample1.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.txt

final var os = System.getProperty("os.name");
System.out.println(os); // Linux

final var file = new File("sample1.txt");
System.out.println(file); // sample1.txt

System.out.println(file.canWrite()); // true
System.out.println(file.setWritable(false)); // true

System.out.println(file.canWrite()); // false

// --- Linux Terminal ---
//$ ls -l sample1.txt
//-r--rw-r-- 1 xxxx xxxx 0 ... sample1.txt
// --- Linux Terminal ---
//$ touch sample2.txt
//$ ls -l sample2.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample2.txt

final var file = new File("sample2.txt");
System.out.println(file); // sample2.txt

System.out.println(file.canWrite()); // true
System.out.println(file.setWritable(false, false)); // true

System.out.println(file.canWrite()); // false

// --- Linux Terminal ---
//$ ls -l sample2.txt
//-r--r--r-- 1 xxxx xxxx 0 ... sample2.txt

int compareTo (File pathname)

Compares two abstract pathnames lexicographically.

final var os = System.getProperty("os.name");
System.out.println(os); // Windows 10

// A path name on Windows is not case-sensitive.
final var file1 = new File("aaa.txt");
final var file2 = new File("AAA.txt");

System.out.println(file1); // aaa.txt
System.out.println(file2); // AAA.txt
System.out.println(file1.compareTo(file2)); // 0
final var file1 = new File("aaa.txt");
final var file2 = new File("bbb.txt");

System.out.println(file1); // aaa.txt
System.out.println(file2); // bbb.txt
System.out.println(file1.compareTo(file2)); // -1
System.out.println(file2.compareTo(file1)); // 1

boolean createNewFile ()

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

System.out.println(file.exists()); // false
System.out.println(file.createNewFile()); // true

System.out.println(file.exists()); // true
System.out.println(file.createNewFile()); // false

static File createTempFile (String prefix, String suffix)

Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

final var ret1 = File.createTempFile("prefix-", "-suffix");

// C:\Users\xxx\AppData\Local\Temp\prefix-1788635824849128964-suffix
System.out.println(ret1);

final var ret2 = File.createTempFile("abcd-", ".txt");

// C:\Users\xxx\AppData\Local\Temp\abcd-2471973508160575501.txt
System.out.println(ret2);

final var ret3 = File.createTempFile("prefix-", null);

// C:\Users\xxx\AppData\Local\Temp\prefix-4955106351488410780.tmp
System.out.println(ret3);

static File createTempFile (String prefix, String suffix, File directory)

Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.

final var dir = new File("R:\\java-work");
System.out.println(dir); // R:\java-work
System.out.println(dir.isDirectory()); // true

final var ret1 = File.createTempFile("prefix-", "-suffix", dir);
System.out.println(ret1); // R:\java-work\prefix-11985693266629058833-suffix

final var ret2 = File.createTempFile("abcd-", ".txt", dir);
System.out.println(ret2); // R:\java-work\abcd-17241334720235449415.txt

final var ret3 = File.createTempFile("prefix-", null, dir);
System.out.println(ret3); // R:\java-work\prefix-16933306792652896919.tmp

boolean delete ()

Deletes the file or directory denoted by this abstract pathname.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

final var dir = new File("R:\\java-work\\dir");
System.out.println(dir); // R:\java-work\dir

System.out.println(file.createNewFile()); // true
System.out.println(dir.mkdir()); // true

// --- PowerShell ---
//PS R:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt

System.out.println(file.delete()); // true
System.out.println(file.exists()); // false

//PS R:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir

System.out.println(dir.delete()); // true
System.out.println(dir.exists()); // false

// --- PowerShell ---
//PS R:\java-work> ls
//<No files / directories>
// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//└─dir
//        aaa.txt
//        bbb.txt

final var dir = new File("R:\\java-work\\dir");
System.out.println(dir); // R:\java-work\dir
System.out.println(dir.isDirectory()); // true

System.out.println(dir.delete()); // false

void deleteOnExit ()

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

public class Main {

    public static void main(String[] args) throws IOException {

        final var file = new File("sample.txt");
        System.out.println("file = " + file);

        System.out.println("file.exists = " + file.exists());

        file.deleteOnExit();
        System.out.println("deleteOnExit : OK!");

        System.out.println("file.exists = " + file.exists());
    }
}

// --- PowerShell ---
//PS R:\java-work> ls -Name
//Main.java
//sample.txt
//
//PS R:\java-work> java Main.java
//file = sample.txt
//file.exists = true
//deleteOnExit : OK!
//file.exists = true
//
//PS R:\java-work> ls -Name
//Main.java

boolean equals (Object obj)

Tests this abstract pathname for equality with the given object.

final var os = System.getProperty("os.name");
System.out.println(os); // Windows 10

// A path name on Windows is not case-sensitive.
final var file1 = new File("aaa.txt");
final var file2 = new File("AAA.txt");

System.out.println(file1); // aaa.txt
System.out.println(file2); // AAA.txt
System.out.println(file1.equals(file2)); // true
final var file1 = new File("aaa.txt");
final var file2 = new File("bbb.txt");

System.out.println(file1); // aaa.txt
System.out.println(file2); // bbb.txt
System.out.println(file1.equals(file2)); // false
System.out.println(file2.equals(file1)); // false

boolean exists ()

Tests whether the file or directory denoted by this abstract pathname exists.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

final var dir = new File("R:\\java-work\\dir");
System.out.println(dir); // R:\java-work\dir

final var nonExistentPath = new File("R:\\java-work\\xxx");
System.out.println(nonExistentPath); // R:\java-work\xxx

System.out.println(file.createNewFile()); // true
System.out.println(dir.mkdir()); // true

// --- PowerShell ---
//PS R:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt

System.out.println(file.isFile()); // true
System.out.println(file.isDirectory()); // false
System.out.println(file.exists()); // true

System.out.println(dir.isFile()); // false
System.out.println(dir.isDirectory()); // true
System.out.println(dir.exists()); // true

System.out.println(nonExistentPath.isFile()); // false
System.out.println(nonExistentPath.isDirectory()); // false
System.out.println(nonExistentPath.exists()); // false

File getAbsoluteFile ()

Returns the absolute form of this abstract pathname.

public class Main {

    public static void main(String[] args) throws IOException {

        final var userDir = System.getProperty("user.dir");
        System.out.println("user.dir = " + userDir);

        {
            final var file = new File("aaa.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("isAbsolute = " + file.isAbsolute());
            System.out.println("getAbsoluteFile = " + file.getAbsoluteFile());
            System.out.println("getAbsolutePath = " + file.getAbsolutePath());
        }
        {
            final var file = new File("R:\\java-work\\bbb.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("isAbsolute = " + file.isAbsolute());
            System.out.println("getAbsoluteFile = " + file.getAbsoluteFile());
            System.out.println("getAbsolutePath = " + file.getAbsolutePath());
        }
    }
}

// --- PowerShell ---
//PS R:\java-work> java Main.java
//user.dir = R:\java-work
//------
//file = aaa.txt
//isAbsolute = false
//getAbsoluteFile = R:\java-work\aaa.txt
//getAbsolutePath = R:\java-work\aaa.txt
//------
//file = R:\java-work\bbb.txt
//isAbsolute = true
//getAbsoluteFile = R:\java-work\bbb.txt
//getAbsolutePath = R:\java-work\bbb.txt

String getAbsolutePath ()

Returns the absolute pathname string of this abstract pathname.

public class Main {

    public static void main(String[] args) throws IOException {

        final var userDir = System.getProperty("user.dir");
        System.out.println("user.dir = " + userDir);

        {
            final var file = new File("aaa.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("isAbsolute = " + file.isAbsolute());
            System.out.println("getAbsoluteFile = " + file.getAbsoluteFile());
            System.out.println("getAbsolutePath = " + file.getAbsolutePath());
        }
        {
            final var file = new File("R:\\java-work\\bbb.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("isAbsolute = " + file.isAbsolute());
            System.out.println("getAbsoluteFile = " + file.getAbsoluteFile());
            System.out.println("getAbsolutePath = " + file.getAbsolutePath());
        }
    }
}

// --- PowerShell ---
//PS R:\java-work> java Main.java
//user.dir = R:\java-work
//------
//file = aaa.txt
//isAbsolute = false
//getAbsoluteFile = R:\java-work\aaa.txt
//getAbsolutePath = R:\java-work\aaa.txt
//------
//file = R:\java-work\bbb.txt
//isAbsolute = true
//getAbsoluteFile = R:\java-work\bbb.txt
//getAbsolutePath = R:\java-work\bbb.txt

File getCanonicalFile ()

Returns the canonical form of this abstract pathname.

public class Main {

    public static void main(String[] args) throws IOException {

        final var userDir = System.getProperty("user.dir");
        System.out.println("user.dir = " + userDir);

        {
            final var file = new File("dir\\aaa.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("getCanonicalFile = " + file.getCanonicalFile());
            System.out.println("getCanonicalPath = " + file.getCanonicalPath());
        }
        {
            final var file = new File("dir\\..\\bbb.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("getCanonicalFile = " + file.getCanonicalFile());
            System.out.println("getCanonicalPath = " + file.getCanonicalPath());
        }
    }
}

// --- PowerShell ---
//PS R:\java-work> java Main.java
//user.dir = R:\java-work
//------
//file = dir\aaa.txt
//getCanonicalFile = R:\java-work\dir\aaa.txt
//getCanonicalPath = R:\java-work\dir\aaa.txt
//------
//file = dir\..\bbb.txt
//getCanonicalFile = R:\java-work\bbb.txt
//getCanonicalPath = R:\java-work\bbb.txt

String getCanonicalPath ()

Returns the canonical pathname string of this abstract pathname.

public class Main {

    public static void main(String[] args) throws IOException {

        final var userDir = System.getProperty("user.dir");
        System.out.println("user.dir = " + userDir);

        {
            final var file = new File("dir\\aaa.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("getCanonicalFile = " + file.getCanonicalFile());
            System.out.println("getCanonicalPath = " + file.getCanonicalPath());
        }
        {
            final var file = new File("dir\\..\\bbb.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("getCanonicalFile = " + file.getCanonicalFile());
            System.out.println("getCanonicalPath = " + file.getCanonicalPath());
        }
    }
}

// --- PowerShell ---
//PS R:\java-work> java Main.java
//user.dir = R:\java-work
//------
//file = dir\aaa.txt
//getCanonicalFile = R:\java-work\dir\aaa.txt
//getCanonicalPath = R:\java-work\dir\aaa.txt
//------
//file = dir\..\bbb.txt
//getCanonicalFile = R:\java-work\bbb.txt
//getCanonicalPath = R:\java-work\bbb.txt

long getFreeSpace ()

Returns the number of unallocated bytes in the partition named by this abstract path name.

final var file = new File("D:");
System.out.println(file); // D:

// --- PowerShell ---
//PS R:\java-work> Get-PSDrive D
//
//Name           Used (GB)     Free (GB) Provider      Root ...
//----           ---------     --------- --------      ---- ...
//D                1665.41        197.48 FileSystem    D:\  ...

System.out.println(file.getTotalSpace()); // 2000263573504
System.out.println(file.getFreeSpace()); // 212039778304
System.out.println(file.getUsableSpace()); // 212039778304

String getName ()

Returns the name of the file or directory denoted by this abstract pathname.

final var file = new File("dir1\\dir2\\aaa.txt");

System.out.println(file.getPath()); // dir1\dir2\aaa.txt
System.out.println(file.getName()); // aaa.txt
System.out.println(file.getParent()); // dir1\dir2

String getParent ()

Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

final var file = new File("dir1\\dir2\\aaa.txt");

System.out.println(file.getPath()); // dir1\dir2\aaa.txt
System.out.println(file.getName()); // aaa.txt
System.out.println(file.getParent()); // dir1\dir2

File getParentFile ()

Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.

final var file = new File("dir1\\dir2\\aaa.txt");
System.out.println(file); // dir1\dir2\aaa.txt

final var parent = file.getParentFile();
System.out.println(parent); // dir1\dir2

final var parentParent = parent.getParentFile();
System.out.println(parentParent); // dir1

String getPath ()

Converts this abstract pathname into a pathname string.

final var file = new File("dir1\\dir2\\aaa.txt");

System.out.println(file.getPath()); // dir1\dir2\aaa.txt
System.out.println(file.getName()); // aaa.txt
System.out.println(file.getParent()); // dir1\dir2

long getTotalSpace ()

Returns the size of the partition named by this abstract pathname.

final var file = new File("D:");
System.out.println(file); // D:

// --- PowerShell ---
//PS R:\java-work> Get-PSDrive D
//
//Name           Used (GB)     Free (GB) Provider      Root ...
//----           ---------     --------- --------      ---- ...
//D                1665.41        197.48 FileSystem    D:\  ...

System.out.println(file.getTotalSpace()); // 2000263573504
System.out.println(file.getFreeSpace()); // 212039778304
System.out.println(file.getUsableSpace()); // 212039778304

long getUsableSpace ()

Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.

final var file = new File("D:");
System.out.println(file); // D:

// --- PowerShell ---
//PS R:\java-work> Get-PSDrive D
//
//Name           Used (GB)     Free (GB) Provider      Root ...
//----           ---------     --------- --------      ---- ...
//D                1665.41        197.48 FileSystem    D:\  ...

System.out.println(file.getTotalSpace()); // 2000263573504
System.out.println(file.getFreeSpace()); // 212039778304
System.out.println(file.getUsableSpace()); // 212039778304

int hashCode ()

Computes a hash code for this abstract pathname.

final var os = System.getProperty("os.name");
System.out.println(os); // Windows 10

// A path name on Windows is not case-sensitive.
final var ret1 = new File("aaa.txt").hashCode();
System.out.println(ret1); // -1239232814

final var ret2 = new File("AAA.TXT").hashCode();
System.out.println(ret2); // -1239232814
final var ret1 = new File("dir1\\dir2\\aaa.txt").hashCode();
System.out.println(ret1); // -639828267

final var ret2 = new File("R:\\java-work\\aaa.txt").hashCode();
System.out.println(ret2); // 503453694

boolean isAbsolute ()

Tests whether this abstract pathname is absolute.

public class Main {

    public static void main(String[] args) throws IOException {

        final var userDir = System.getProperty("user.dir");
        System.out.println("user.dir = " + userDir);

        {
            final var file = new File("aaa.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("isAbsolute = " + file.isAbsolute());
            System.out.println("getAbsoluteFile = " + file.getAbsoluteFile());
            System.out.println("getAbsolutePath = " + file.getAbsolutePath());
        }
        {
            final var file = new File("R:\\java-work\\bbb.txt");

            System.out.println("------");
            System.out.println("file = " + file);
            System.out.println("isAbsolute = " + file.isAbsolute());
            System.out.println("getAbsoluteFile = " + file.getAbsoluteFile());
            System.out.println("getAbsolutePath = " + file.getAbsolutePath());
        }
    }
}

// --- PowerShell ---
//PS R:\java-work> java Main.java
//user.dir = R:\java-work
//------
//file = aaa.txt
//isAbsolute = false
//getAbsoluteFile = R:\java-work\aaa.txt
//getAbsolutePath = R:\java-work\aaa.txt
//------
//file = R:\java-work\bbb.txt
//isAbsolute = true
//getAbsoluteFile = R:\java-work\bbb.txt
//getAbsolutePath = R:\java-work\bbb.txt

boolean isDirectory ()

Tests whether the file denoted by this abstract pathname is a directory.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

final var dir = new File("R:\\java-work\\dir");
System.out.println(dir); // R:\java-work\dir

final var nonExistentPath = new File("R:\\java-work\\xxx");
System.out.println(nonExistentPath); // R:\java-work\xxx

System.out.println(file.createNewFile()); // true
System.out.println(dir.mkdir()); // true

// --- PowerShell ---
//PS R:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt

System.out.println(file.isFile()); // true
System.out.println(file.isDirectory()); // false
System.out.println(file.exists()); // true

System.out.println(dir.isFile()); // false
System.out.println(dir.isDirectory()); // true
System.out.println(dir.exists()); // true

System.out.println(nonExistentPath.isFile()); // false
System.out.println(nonExistentPath.isDirectory()); // false
System.out.println(nonExistentPath.exists()); // false

boolean isFile ()

Tests whether the file denoted by this abstract pathname is a normal file.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

final var dir = new File("R:\\java-work\\dir");
System.out.println(dir); // R:\java-work\dir

final var nonExistentPath = new File("R:\\java-work\\xxx");
System.out.println(nonExistentPath); // R:\java-work\xxx

System.out.println(file.createNewFile()); // true
System.out.println(dir.mkdir()); // true

// --- PowerShell ---
//PS R:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//d---- dir
//-a--- aaa.txt

System.out.println(file.isFile()); // true
System.out.println(file.isDirectory()); // false
System.out.println(file.exists()); // true

System.out.println(dir.isFile()); // false
System.out.println(dir.isDirectory()); // true
System.out.println(dir.exists()); // true

System.out.println(nonExistentPath.isFile()); // false
System.out.println(nonExistentPath.isDirectory()); // false
System.out.println(nonExistentPath.exists()); // false

boolean isHidden ()

Tests whether the file named by this abstract pathname is a hidden file.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt
System.out.println(file.createNewFile()); // true

System.out.println(file.isHidden()); // false

// --- PowerShell ---
//PS R:\java-work> ls -Force | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//-a--- aaa.txt

Files.setAttribute(file.toPath(), "dos:hidden", true);

System.out.println(file.isHidden()); // true

// --- PowerShell ---
//PS R:\java-work> ls -Force | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//-a-h- aaa.txt

long lastModified ()

Returns the time that the file denoted by this abstract pathname was last modified.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt
System.out.println(file.createNewFile()); // true

final var zoneId = ZoneId.systemDefault();
System.out.println(zoneId); // Asia/Tokyo

final var dateTime1 = ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, zoneId);
System.out.println(dateTime1); // 2100-01-01T00:00+09:00[Asia/Tokyo]

final var ret = file.setLastModified(dateTime1.toInstant().toEpochMilli());
System.out.println(ret); // true

// --- PowerShell ---
//PS R:\java-work> ls | Format-Table -Property LastWriteTime, Name
//
//LastWriteTime      Name
//-------------      ----
//2100/01/01 0:00:00 aaa.txt

final var lastModified = file.lastModified();
System.out.println(lastModified); // 4102412400000

final var dateTime2 = ZonedDateTime.ofInstant(
        Instant.ofEpochMilli(lastModified), zoneId);
System.out.println(dateTime2); // 2100-01-01T00:00+09:00[Asia/Tokyo]

long length ()

Returns the length of the file denoted by this abstract pathname.

// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//│  aaa.txt
//│  bbb.txt
//│
//└─dir
//        ccc.txt
//
//PS R:\java-work> ls | Format-Table -Property Length, Name
//
//Length Name
//------ ----
//       dir
//5      aaa.txt
//1000   bbb.txt
//
//PS R:\java-work> ls dir | Format-Table -Property Length, Name
//
//Length Name
//------ ----
//    12 ccc.txt

final var file1 = new File("R:\\java-work\\aaa.txt");
System.out.println(file1); // R:\java-work\aaa.txt
System.out.println(file1.length()); // 5

final var file2 = new File("R:\\java-work\\bbb.txt");
System.out.println(file2); // R:\java-work\bbb.txt
System.out.println(file2.length()); // 1000

final var dir = new File("R:\\java-work\\dir");
System.out.println(dir); // R:\java-work\dir
System.out.println(dir.length()); // 0

String[] list ()

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//│  aaa.txt
//│  bbb.txt
//│
//└─dir
//        ccc.txt
//        ddd.txt

{
    final var dir = new File("R:\\java-work");
    System.out.println(dir); // R:\java-work

    final var ret = dir.list();
    System.out.println(Arrays.toString(ret)); // [aaa.txt, bbb.txt, dir]
}
{
    final var dir = new File("R:\\java-work\\dir");
    System.out.println(dir); // R:\java-work\dir

    final var ret = dir.list();
    System.out.println(Arrays.toString(ret)); // [ccc.txt, ddd.txt]
}

String[] list (FilenameFilter filter)

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

// --- PowerShell ---
//PS R:\java-work> ls -Name
//aaa.txt
//bbb.jpg
//ccc.txt
//ddd.jpg

final var dir = new File("R:\\java-work");
System.out.println(dir); // R:\java-work

final var filter = new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".txt");
    }
};

final var ret1 = dir.list();
System.out.println(Arrays.toString(ret1)); // [aaa.txt, bbb.jpg, ccc.txt, ddd.jpg]

final var ret2 = dir.list(filter);
System.out.println(Arrays.toString(ret2)); // [aaa.txt, ccc.txt]

File[] listFiles ()

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//│  aaa.txt
//│  bbb.txt
//│
//└─dir
//        ccc.txt
//        ddd.txt

{
    final var dir = new File("R:\\java-work");
    System.out.println(dir); // R:\java-work

    final var files = dir.listFiles();
    if (files != null) {
        System.out.println("-- listFiles --");
        for (final var file : files) {
            System.out.println(file);
        }
    }

    // Result
    // ↓
    //-- listFiles --
    //R:\java-work\aaa.txt
    //R:\java-work\bbb.txt
    //R:\java-work\dir
}
{
    final var dir = new File("R:\\java-work\\dir");
    System.out.println(dir); // R:\java-work\dir

    final var files = dir.listFiles();
    if (files != null) {
        System.out.println("-- listFiles --");
        for (final var file : files) {
            System.out.println(file);
        }
    }

    // Result
    // ↓
    //-- listFiles --
    //R:\java-work\dir\ccc.txt
    //R:\java-work\dir\ddd.txt
}

File[] listFiles (FileFilter filter)

Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

// --- PowerShell ---
//PS R:\java-work> ls -Name
//aaa.txt
//bbb.jpg
//ccc.txt
//ddd.jpg

final var dir = new File("R:\\java-work");
System.out.println(dir); // R:\java-work

final var filter = new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        return pathname.getName().endsWith(".txt");
    }
};

final var files = dir.listFiles(filter);
if (files != null) {
    System.out.println("-- listFiles --");
    for (final var file : files) {
        System.out.println(file);
    }
}

// Result
// ↓
//-- listFiles --
//R:\java-work\aaa.txt
//R:\java-work\ccc.txt

File[] listFiles (FilenameFilter filter)

Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

// --- PowerShell ---
//PS R:\java-work> ls -Name
//aaa.txt
//bbb.jpg
//ccc.txt
//ddd.jpg

final var dir = new File("R:\\java-work");
System.out.println(dir); // R:\java-work

final var filter = new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".txt");
    }
};

final var files = dir.listFiles(filter);
if (files != null) {
    System.out.println("-- listFiles --");
    for (final var file : files) {
        System.out.println(file);
    }
}

// Result
// ↓
//-- listFiles --
//R:\java-work\aaa.txt
//R:\java-work\ccc.txt

static File[] listRoots ()

List the available filesystem roots.

final var roots = File.listRoots();
for (final var root : roots) {
    System.out.println(root);
}

// Result
// ↓
//C:\
//D:\
//...

boolean mkdir ()

Creates the directory named by this abstract pathname.

// --- PowerShell ---
//PS R:\java-work> ls -Name
//<No files / directories>

final var dir1 = new File("R:\\java-work\\dir1");
System.out.println(dir1); // R:\java-work\dir1

System.out.println(dir1.mkdir()); // true

// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//└─dir1

final var dir2 = new File(dir1, "dir2");
System.out.println(dir2); // R:\java-work\dir1\dir2

System.out.println(dir2.mkdir()); // true

// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//└─dir1
//    └─dir2
// --- PowerShell ---
//PS R:\java-work> ls -Name
//<No files / directories>

final var dir = new File("R:\\java-work\\dir1\\dir2");
System.out.println(dir); // R:\java-work\dir1\dir2

System.out.println(dir.mkdir()); // false

// --- PowerShell ---
//PS R:\java-work> ls -Name
//<No files / directories>

boolean mkdirs ()

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.

// --- PowerShell ---
//PS R:\java-work> ls -Name
//<No files / directories>

final var dir = new File("R:\\java-work\\dir1\\dir2");
System.out.println(dir); // R:\java-work\dir1\dir2

System.out.println(dir.mkdirs()); // true

// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//└─dir1
//    └─dir2

boolean renameTo (File dest)

Renames the file denoted by this abstract pathname.

final var src = new File("R:\\java-work\\src.txt");
System.out.println(src); // R:\java-work\src.txt

final var dst = new File("R:\\java-work\\dst.txt");
System.out.println(dst); // R:\java-work\dst.txt

System.out.println(src.exists()); // true
System.out.println(dst.exists()); // false

// --- PowerShell ---
//PS R:\java-work> ls -Name
//src.txt
//PS R:\java-work> cat src.txt
//abcd

System.out.println(src.renameTo(dst)); // true

System.out.println(src.exists()); // false
System.out.println(dst.exists()); // true

// --- PowerShell ---
//PS R:\java-work> ls -Name
//dst.txt
//PS R:\java-work> cat dst.txt
//abcd

boolean setExecutable (boolean executable)

A convenience method to set the owner's execute permission for this abstract pathname.

// --- Linux Terminal ---
//$ touch sample1.sh
//$ ls -l sample1.sh
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.sh

final var os = System.getProperty("os.name");
System.out.println(os); // Linux

final var file = new File("sample1.sh");
System.out.println(file); // sample1.sh

System.out.println(file.canExecute()); // false
System.out.println(file.setExecutable(true)); // true

System.out.println(file.canExecute()); // true

// --- Linux Terminal ---
//$ ls -l sample1.sh
//-rwxrw-r-- 1 xxxx xxxx 0 ... sample1.sh
// --- Linux Terminal ---
//$ touch sample2.sh
//$ ls -l sample2.sh
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample2.sh

final var file = new File("sample2.sh");
System.out.println(file); // sample2.sh

System.out.println(file.canExecute()); // false
System.out.println(file.setExecutable(true, false)); // true

System.out.println(file.canExecute()); // true

// --- Linux Terminal ---
//$ ls -l sample2.sh
//-rwxrwxr-x 1 xxxx xxxx 0 ... sample2.sh

boolean setExecutable (boolean executable, boolean ownerOnly)

Sets the owner's or everybody's execute permission for this abstract pathname.

// --- Linux Terminal ---
//$ touch sample1.sh
//$ ls -l sample1.sh
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.sh

final var os = System.getProperty("os.name");
System.out.println(os); // Linux

final var file = new File("sample1.sh");
System.out.println(file); // sample1.sh

System.out.println(file.canExecute()); // false
System.out.println(file.setExecutable(true)); // true

System.out.println(file.canExecute()); // true

// --- Linux Terminal ---
//$ ls -l sample1.sh
//-rwxrw-r-- 1 xxxx xxxx 0 ... sample1.sh
// --- Linux Terminal ---
//$ touch sample2.sh
//$ ls -l sample2.sh
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample2.sh

final var file = new File("sample2.sh");
System.out.println(file); // sample2.sh

System.out.println(file.canExecute()); // false
System.out.println(file.setExecutable(true, false)); // true

System.out.println(file.canExecute()); // true

// --- Linux Terminal ---
//$ ls -l sample2.sh
//-rwxrwxr-x 1 xxxx xxxx 0 ... sample2.sh

boolean setLastModified (long time)

Sets the last-modified time of the file or directory named by this abstract pathname.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt
System.out.println(file.createNewFile()); // true

final var zoneId = ZoneId.systemDefault();
System.out.println(zoneId); // Asia/Tokyo

final var dateTime1 = ZonedDateTime.of(2100, 1, 1, 0, 0, 0, 0, zoneId);
System.out.println(dateTime1); // 2100-01-01T00:00+09:00[Asia/Tokyo]

final var ret = file.setLastModified(dateTime1.toInstant().toEpochMilli());
System.out.println(ret); // true

// --- PowerShell ---
//PS R:\java-work> ls | Format-Table -Property LastWriteTime, Name
//
//LastWriteTime      Name
//-------------      ----
//2100/01/01 0:00:00 aaa.txt

final var lastModified = file.lastModified();
System.out.println(lastModified); // 4102412400000

final var dateTime2 = ZonedDateTime.ofInstant(
        Instant.ofEpochMilli(lastModified), zoneId);
System.out.println(dateTime2); // 2100-01-01T00:00+09:00[Asia/Tokyo]

boolean setReadable (boolean readable)

A convenience method to set the owner's read permission for this abstract pathname.

// --- Linux Terminal ---
//$ touch sample1.txt
//$ ls -l sample1.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.txt

final var os = System.getProperty("os.name");
System.out.println(os); // Linux

final var file = new File("sample1.txt");
System.out.println(file); // sample1.txt

System.out.println(file.canRead()); // true
System.out.println(file.setReadable(false)); // true

System.out.println(file.canRead()); // false

// --- Linux Terminal ---
//$ ls -l sample1.txt
//--w-rw-r-- 1 xxxx xxxx 0 ... sample1.txt
// --- Linux Terminal ---
//$ touch sample2.txt
//$ ls -l sample2.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample2.txt

final var file = new File("sample2.txt");
System.out.println(file); // sample2.txt

System.out.println(file.canRead()); // true
System.out.println(file.setReadable(false, false)); // true

System.out.println(file.canRead()); // false

// --- Linux Terminal ---
//$ ls -l sample2.txt
//--w--w---- 1 xxxx xxxx 0 ... sample2.txt

boolean setReadable (boolean readable, boolean ownerOnly)

Sets the owner's or everybody's read permission for this abstract pathname.

// --- Linux Terminal ---
//$ touch sample1.txt
//$ ls -l sample1.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.txt

final var os = System.getProperty("os.name");
System.out.println(os); // Linux

final var file = new File("sample1.txt");
System.out.println(file); // sample1.txt

System.out.println(file.canRead()); // true
System.out.println(file.setReadable(false)); // true

System.out.println(file.canRead()); // false

// --- Linux Terminal ---
//$ ls -l sample1.txt
//--w-rw-r-- 1 xxxx xxxx 0 ... sample1.txt
// --- Linux Terminal ---
//$ touch sample2.txt
//$ ls -l sample2.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample2.txt

final var file = new File("sample2.txt");
System.out.println(file); // sample2.txt

System.out.println(file.canRead()); // true
System.out.println(file.setReadable(false, false)); // true

System.out.println(file.canRead()); // false

// --- Linux Terminal ---
//$ ls -l sample2.txt
//--w--w---- 1 xxxx xxxx 0 ... sample2.txt

boolean setReadOnly ()

Marks the file or directory named by this abstract pathname so that only read operations are allowed.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt
System.out.println(file.createNewFile()); // true

// --- PowerShell ---
//PS R:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//-a--- aaa.txt

System.out.println(file.setReadOnly()); // true

// --- PowerShell ---
//PS R:\java-work> ls | Format-Table -Property Mode, Name
//
//Mode  Name
//----  ----
//-ar-- aaa.txt

boolean setWritable (boolean writable)

A convenience method to set the owner's write permission for this abstract pathname.

// --- Linux Terminal ---
//$ touch sample1.txt
//$ ls -l sample1.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.txt

final var os = System.getProperty("os.name");
System.out.println(os); // Linux

final var file = new File("sample1.txt");
System.out.println(file); // sample1.txt

System.out.println(file.canWrite()); // true
System.out.println(file.setWritable(false)); // true

System.out.println(file.canWrite()); // false

// --- Linux Terminal ---
//$ ls -l sample1.txt
//-r--rw-r-- 1 xxxx xxxx 0 ... sample1.txt
// --- Linux Terminal ---
//$ touch sample2.txt
//$ ls -l sample2.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample2.txt

final var file = new File("sample2.txt");
System.out.println(file); // sample2.txt

System.out.println(file.canWrite()); // true
System.out.println(file.setWritable(false, false)); // true

System.out.println(file.canWrite()); // false

// --- Linux Terminal ---
//$ ls -l sample2.txt
//-r--r--r-- 1 xxxx xxxx 0 ... sample2.txt

boolean setWritable (boolean writable, boolean ownerOnly)

Sets the owner's or everybody's write permission for this abstract pathname.

// --- Linux Terminal ---
//$ touch sample1.txt
//$ ls -l sample1.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample1.txt

final var os = System.getProperty("os.name");
System.out.println(os); // Linux

final var file = new File("sample1.txt");
System.out.println(file); // sample1.txt

System.out.println(file.canWrite()); // true
System.out.println(file.setWritable(false)); // true

System.out.println(file.canWrite()); // false

// --- Linux Terminal ---
//$ ls -l sample1.txt
//-r--rw-r-- 1 xxxx xxxx 0 ... sample1.txt
// --- Linux Terminal ---
//$ touch sample2.txt
//$ ls -l sample2.txt
//-rw-rw-r-- 1 xxxx xxxx 0 ... sample2.txt

final var file = new File("sample2.txt");
System.out.println(file); // sample2.txt

System.out.println(file.canWrite()); // true
System.out.println(file.setWritable(false, false)); // true

System.out.println(file.canWrite()); // false

// --- Linux Terminal ---
//$ ls -l sample2.txt
//-r--r--r-- 1 xxxx xxxx 0 ... sample2.txt

Path toPath ()

Returns a java.nio.file.Path object constructed from this abstract path.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

final var path = file.toPath();
System.out.println(path); // R:\java-work\aaa.txt

Files.writeString(path, "abcd");

// --- PowerShell ---
//PS R:\java-work> ls -Name
//aaa.txt
//PS R:\java-work> cat aaa.txt
//abcd

String toString ()

Returns the pathname string of this abstract pathname.

final var file = new File("aaa.txt");
final var str = file.toString();
System.out.println(str); // aaa.txt
final var dir = new File("R:\\java-work\\dir");
final var str = dir.toString();
System.out.println(str); // R:\java-work\dir

URI toURI ()

Constructs a file: URI that represents this abstract pathname.

final var file = new File("R:\\java-work\\aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt

final var uri = file.toURI();
System.out.println(uri); // file:/R:/java-work/aaa.txt

URL toURL ()

Deprecated. This method does not automatically escape characters that are illegal in URLs.

Deprecated.


Related posts

To top of page