Java : File 示例

File (Java SE 22 & JDK 22) 示例。
您将在大多数 File 方法中找到代码示例。

警告 :

  • File 类是传统的 API。 建议使用较新的 API PathFiles

注解 :

  • 本文可能使用了翻译软件以方便阅读。 另请查看英文原文

简介

文件和目录路径名的抽象表示。 (机器翻译)

Class diagram

注释 :

  • 本文中的大部分代码示例都在 Windows 上运行。 不过,也有一些代码示例是在 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

系统相关的路径分隔符,为方便起见,以字符串表示。 (机器翻译)

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

系统相关的路径分隔符。 (机器翻译)

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

系统相关的默认名称分隔符,为方便起见,以字符串表示。 (机器翻译)

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

系统相关的默认名称分隔符。 (机器翻译)

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)

从父抽象路径名和子路径名字符串创建一个新的文件实例。 (机器翻译)

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)

通过将给定的路径名​​字符串转换为抽象路径名来创建一个新的 File 实例。 (机器翻译)

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)

根据父路径名字符串和子路径名字符串创建一个新的文件实例。 (机器翻译)

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)

通过将给定的文件:URI 转换为抽象路径名来创建一个新的 File 实例。 (机器翻译)

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 ()

测试应用程序是否可以执行此抽象路径名表示的文件。 (机器翻译)

// --- 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 ()

测试应用程序是否可以读取此抽象路径名表示的文件。 (机器翻译)

// --- 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 ()

测试应用程序是否可以修改此抽象路径名表示的文件。 (机器翻译)

// --- 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)

按字典顺序比较两个抽象路径名。 (机器翻译)

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 ()

当且仅当不存在具有该名称的文件时,才原子地创建以此抽象路径名命名的新的空文件。 (机器翻译)

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)

在默认临时文件目录中创建一个空文件,使用给定的前缀和后缀生成其名称。 (机器翻译)

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)

在指定目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称。 (机器翻译)

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 ()

删除此抽象路径名表示的文件或目录。 (机器翻译)

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 ()

请求在虚拟机终止时删除此抽象路径名表示的文件或目录。 (机器翻译)

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)

测试此抽象路径名是否与给定的对象相等。 (机器翻译)

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 ()

测试此抽象路径名表示的文件或目录是否存在。 (机器翻译)

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 ()

返回此抽象路径名的绝对形式。 (机器翻译)

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 ()

返回此抽象路径名的绝对路径名字符串。 (机器翻译)

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 ()

返回此抽象路径名的规范形式。 (机器翻译)

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 ()

返回此抽象路径名的规范路径名字符串。 (机器翻译)

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 ()

返回此抽象路径名命名的分区中未分配的字节数。 (机器翻译)

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 ()

返回此抽象路径名表示的文件或目录的名称。 (机器翻译)

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 ()

返回此抽象路径名的父路径名字符串,如果此路径名未指定父目录,则返回 null。 (机器翻译)

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 ()

返回此抽象路径名的父级的抽象路径名,如果此路径名没有指定父目录,则返回 null。 (机器翻译)

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 ()

将此抽象路径名转换为路径名字符串。 (机器翻译)

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 ()

返回此抽象路径名命名的分区的大小。 (机器翻译)

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 ()

返回此虚拟机在此抽象路径名命名的分区上可用的字节数。 (机器翻译)

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 ()

计算此抽象路径名的哈希码。 (机器翻译)

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 ()

测试此抽象路径名是否是绝对的。 (机器翻译)

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 ()

测试此抽象路径名表示的文件是否是目录。 (机器翻译)

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 ()

测试此抽象路径名表示的文件是否是普通文件。 (机器翻译)

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 ()

测试此抽象路径名命名的文件是否是隐藏文件。 (机器翻译)

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 ()

返回此抽象路径名表示的文件最后修改的时间。 (机器翻译)

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 ()

返回此抽象路径名表示的文件的长度。 (机器翻译)

// --- 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 ()

返回一个字符串数组,其中包含此抽象路径名所表示的目录中的文件和目录的名称。 (机器翻译)

// --- 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)

返回一个字符串数组,其中包含此抽象路径名所表示的目录中满足指定过滤器的文件和目录。 (机器翻译)

// --- 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 ()

返回一个抽象路径名数组,表示该抽象路径名所表示的目录中的文件。 (机器翻译)

// --- 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)

返回一个抽象路径名数组,表示此抽象路径名所表示的目录中满足指定过滤器的文件和目录。 (机器翻译)

// --- 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)

返回一个抽象路径名数组,表示此抽象路径名所表示的目录中满足指定过滤器的文件和目录。 (机器翻译)

// --- 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 ()

列出可用的文件系统根。 (机器翻译)

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

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

boolean mkdir ()

创建由此抽象路径名命名的目录。 (机器翻译)

// --- 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 ()

创建由此抽象路径名命名的目录,包括任何必要但不存在的父目录。 (机器翻译)

// --- 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)

重命名此抽象路径名表示的文件。 (机器翻译)

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)

一种便捷方法来设置此抽象路径名的所有者的执行权限。 (机器翻译)

// --- 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)

设置此抽象路径名的所有者或每个人的执行权限。 (机器翻译)

// --- 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)

设置此抽象路径名命名的文件或目录的最后修改时间。 (机器翻译)

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)

一种便捷方法来设置此抽象路径名的所有者的读取权限。 (机器翻译)

// --- 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)

设置此抽象路径名的所有者或所有人的读取权限。 (机器翻译)

// --- 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 ()

标记此抽象路径名命名的文件或目录,以便只允许读取操作。 (机器翻译)

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)

一种便捷的方法,用于设置此抽象路径名的所有者的写权限。 (机器翻译)

// --- 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)

设置此抽象路径名的所有者或所有人的写权限。 (机器翻译)

// --- 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 ()

返回从此抽象路径构造的 java.nio.file.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 ()

返回此抽象路径名的路径名字符串。 (机器翻译)

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 ()

构造一个文件:表示此抽象路径名的 URI。 (机器翻译)

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 ()

已弃用。此方法不会自动转义 URL 中的非法字符。 (机器翻译)

Deprecated.


相关文章

To top of page