首頁  >  文章  >  Java  >  如何使用Java中的File類別方法?

如何使用Java中的File類別方法?

WBOY
WBOY轉載
2023-04-23 18:49:07991瀏覽

File類別概述

File類別是java.io套件下代表與平台無關的檔案和目錄。 File可以新建、刪除、重新命名檔案和目錄,但不能存取檔案內容本身,如果需要存取內容的話,則需要透過輸入/輸出流來存取。

File類別可以使用檔案路徑字串建立File實例,路徑既可以是絕對路徑,也可以是相對路徑。一般相對路徑的話是由系統屬性user.dir指定,即為Java VM所在路徑。

File類別常用建構器

    /**
     * Creates a new <code>File</code> instance by converting the given
     * pathname string into an abstract pathname.  If the given string is
     * the empty string, then the result is the empty abstract pathname.
     *
     * @param   pathname  A pathname string
     * @throws  NullPointerException
     *          If the <code>pathname</code> argument is <code>null</code>
     */
    public File(String pathname) {
        if (pathname == null) {
            throw new NullPointerException();
        }
        this.path = fs.normalize(pathname);
        this.prefixLength = fs.prefixLength(this.path);
    }

File類別常用方法

  • #public String getName():傳回File物件鎖定表示的檔案名稱或目錄名(若為目錄,則回傳的是最後一級子目錄)。

  • public String getParent():傳回此File物件所對應的路徑名,傳回String類型。

  • public File getParentFile():傳回此File物件的父目錄,傳回File型別。

  • public String getPath():傳回此File物件所對應的路徑名,傳回String類型。

  • public boolean isAbsolute():判斷File物件所對應的檔案或目錄是否為絕對路徑。

  • public String getAbsolutePath():傳回此File物件所對應的絕對路徑,傳回String類型。

  • public String getCanonicalPath() throws IOException:

  • public File getCanonicalFile() throws IOException:

  • #public File getAbsoluteFile():傳回此File物件所對應的絕對路徑,傳回File型別。

  • public boolean canRead():判斷此File物件所對應的檔案或目錄是否可讀。

  • public boolean canWrite():判斷此File物件所對應的檔案或目錄是否可寫入。

  • public boolean canExecute():判斷此File物件所對應的檔案或目錄是否可執行。

  • public boolean exists():判斷此File物件所對應的檔案或目錄是否存在。

  • public boolean isDirectory():判斷此File物件是否為目錄。

  • public boolean isFile():判斷此File物件是否為檔案。

  • public boolean isHidden():判斷此File物件是否為隱藏。

  • public 長者 lastModified():傳回該File物件最後修改的時間戳,我們可以透過SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;進行格式化為時間日期展示。

  • public boolean setLastModified(long time):設定該File物件最後修改的時間戳記。

  • public long length():傳回該File物件的檔案內容長度。

  • public boolean createNewFile() throws IOException:當此File物件所對應的文件不存在時,該方法會新建一個該File物件所指定的新文件,如果已建立成功,傳回true;否則,回傳false。

  • public boolean delete():刪除File物件所對應的檔案或目錄,刪除成功,傳回true;否則,傳回false。

  • public void deleteOnExit():Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.意思是在VM關閉的時候,刪除該檔案或目錄,不像delete()方法一呼叫就刪除。一般用於臨時文件比較合適。

  • public String[] list():列出File物件的所有子檔案名稱和路徑名,傳回的是String陣列。

  • public File[] listFiles():列出File物件的所有子檔案嗎和路徑名,傳回的是File陣列。

  • public boolean mkdir():建立目錄,並且只能在已有的父類別下方建立子類,如果父類別沒有,那麼就無法建立子類別。

  • public boolean mkdirs():也是建立目錄,而且可以在父資料夾不存在的情況下,建立子資料夾,順便將父資料夾也建立了,遞歸創建。

  • public boolean renameTo(File dest):重新命名此File物件所對應的檔案或目錄,如果重新命名成功,則傳回true;否則,傳回false。

  • public boolean setReadOnly():設定此File物件為唯讀權限。

  • public boolean setWritable(boolean writable, boolean ownerOnly):寫權限設置,writable如果為true,允許寫訪問權限;如果為false,寫訪問權限是不允許的。 ownerOnly如果為true,則寫入存取權限僅適用於擁有者;否則它適用於所有人。

  • public boolean setWritable(boolean writable): 底層實作是:透過setWritable(writable, true)實現,預設是僅適用於檔案或目錄擁有者。

    public boolean setWritable(boolean writable) {
        return setWritable(writable, true);
    }
  • public boolean setReadable(boolean readable, boolean ownerOnly):讀取權限設置,readable如果為true,允許讀取存取權限;如果為false,讀取訪問權限是不允許的。 ownerOnly如果為true,則讀取存取權限僅適用於擁有者;否則它適用於所有人。

  • public boolean setReadable(boolean readable): 底层实现是:通过setReadable(readable, true)实现,默认是仅适用于文件或目录所有者。

    public boolean setReadable(boolean readable) {
        return setReadable(readable, true);
    }
  • public boolean setExecutable(boolean executable, boolean ownerOnly):执行权限设置,executable如果为true,允许执行访问权限;如果为false,执行访问权限是不允许的。ownerOnly如果为true,则执行访问权限仅适用于所有者;否则它适用于所有人。

  • public boolean setExecutable(boolean executable): 底层实现是:通过setExecutable(executable, true)实现,默认是仅适用于文件或目录所有者。

    public boolean setExecutable(boolean executable) {
        return setExecutable(executable, true);
    }
  • public static File[] listRoots():列出系统所有的根路径,可以直接通过File类进行调用。

  • public long getTotalSpace():返回总空间大小,默认单位为字节。

  • public long getFreeSpace():Returns the number of unallocated bytes in the partition,返回未被分配空间大小,默认单位为字节。

  • public long getUsableSpace():Returns the number of bytes available to this virtual machine on the partition,返回可用空间大小,默认单位为字节。

  • public Path toPath():返回该File对象的Path对象。

  • public static File createTempFile(String prefix, String suffix) throws IOException:在默认存放临时文件目录中,创建一个临时空文件。可以直接使用File类来调用,使用给定前缀、系统生成的随机数以及给定后缀作为文件名。prefix至少3字节长。如果suffix设置为null,则默认后缀为.tmp。

  • public static File createTempFile(String prefix, String suffix, File directory):在指定的临时文件目录directort中,创建一个临时空文件。可以直接使用File类来调用,使用给定前缀、系统生成的随机数以及给定后缀作为文件名。prefix至少3字节长。如果suffix设置为null,则默认后缀为.tmp。

常用方法示例

1)运行主类

package com.example.andya.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.text.SimpleDateFormat;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\LIAOJIANYA\\Desktop\\filetest\\filedir02\\FileTest.txt");
        System.out.println("getName(): " + file.getName());
        System.out.println("getParent(): " + file.getParent());
        System.out.println("getParentFile(): " + file.getParentFile());
        System.out.println("getAbsolutePath(): " + file.getAbsolutePath());
        System.out.println("getAbsoluteFile(): " + file.getAbsoluteFile());
        System.out.println("getAbsoluteFile().getParent(): " + file.getAbsoluteFile().getParent());
        System.out.println("getPath(): " + file.getPath());
        System.out.println("isAbsolute(): " + file.isAbsolute());
        System.out.println("getCanonicalPath(): " + file.getCanonicalPath());
        System.out.println("getCanonicalFile(): " + file.getCanonicalFile());
        System.out.println("canRead(): " + file.canRead());
        System.out.println("canWrite(): " + file.canWrite());
        System.out.println("canExecute(): " + file.canExecute());
        System.out.println("exists(): " + file.exists());
        System.out.println("isDirectory(): " + file.isDirectory());
        System.out.println("isFile(): " + file.isFile());
        System.out.println("isHidden(): " + file.isHidden());
        System.out.println(file.setLastModified(1546275661));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("lastModified(): " + simpleDateFormat.format(file.lastModified()));
        //在里面写了"123"这三个数字
        System.out.println("length(): " + file.length());
        File newFile01 = new File("C:\\Users\\LIAOJIANYA\\Desktop\\filetest\\filedir02\\FileTest1.txt");
        newFile01.createNewFile();
        newFile01.delete();

        File newDir1 = new File("C:\\Users\\LIAOJIANYA\\Desktop\\filetest\\filedir02\\dir1");
        System.out.println("mkdir(): " + newDir1.mkdir());

        File newDir2 = new File("C:\\Users\\LIAOJIANYA\\Desktop\\filetest\\filedir02\\dir2\\dir2-1");
        System.out.println("mkdirs(): " + newDir2.mkdirs());

        String[] fileList = file.getParentFile().list();
        System.out.println("========上一级目录下的所有文件和路径=========");
        for (String fileName : fileList) {
            System.out.println(fileName);
        }
        System.out.println("file重命名:" + file.renameTo(new File("C:\\Users\\LIAOJIANYA\\Desktop\\filetest\\filedir02\\FileTest.txt")));

        System.out.println("========上一级目录下的所有文件和目录=========");
        File[] files = file.getParentFile().listFiles();
        for (File fileName : files) {
            System.out.println(fileName.getName());
        }

        System.out.println("canRead(): " + file.canRead());

        //人为改为不可写
        System.out.println("setWritable(): " + file.setWritable(false, false));
        System.out.println("canWrite(): "  + file.canWrite());

        System.out.println("canExecute(): " + file.canExecute());

        System.out.println("========相对路径=========");
        //默认相对路径是user.dir即为当前工程所在位置
        System.out.println("user.dir:" + System.getProperty("user.dir"));
        File newFile = new File("test.txt");
        System.out.println("newFile文件是否存在:" + newFile.exists());
        newFile.createNewFile();
        System.out.println("新建newFile文件后是否存在:" + newFile.exists() + ", 路径为:" + newFile.getAbsolutePath());
        System.out.println("getName(): " + newFile.getName());
        System.out.println("getParent(): " + newFile.getParent());
        System.out.println("getParentFile(): " + newFile.getParentFile());
        System.out.println("getAbsolutePath(): " + newFile.getAbsolutePath());
        System.out.println("getAbsoluteFile(): " + newFile.getAbsoluteFile());
        System.out.println("getAbsoluteFile().getParent(): " + newFile.getAbsoluteFile().getParent());
        System.out.println("getPath(): " + newFile.getPath());
        System.out.println("isAbsolute(): " + newFile.isAbsolute());
        System.out.println("getCanonicalPath(): " + newFile.getCanonicalPath());
        System.out.println("getCanonicalFile(): " + newFile.getCanonicalFile());
        URI uri = newFile.toURI();
        System.out.println("URI:" + uri.toString());

        File[] listRoots = File.listRoots();
        System.out.println("========系统根目录下的所有文件和路径=========");
        for (File root : listRoots) {
            System.out.println(root);
        }

        System.out.println("getTotalSpace(): " + file.getTotalSpace()/1024/1024/1024 + " G");
        System.out.println("getFreeSpace(): " + file.getFreeSpace()/1024/1024/1024 + " G");
        System.out.println("getUsableSpace(): " + file.getUsableSpace()/1024/1024/1024 + " G");
        Path path = file.toPath();
        System.out.println("Path: " + path);
        SpringApplication.run(DemoApplication.class, args);
    }
}

2)运行结果:

getName(): FileTest.txt
getParent(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02
getParentFile(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02
getAbsolutePath(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
getAbsoluteFile(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
getAbsoluteFile().getParent(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02
getPath(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
isAbsolute(): true
getCanonicalPath(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
getCanonicalFile(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
canRead(): true
canWrite(): false
canExecute(): true
exists(): true
isDirectory(): false
isFile(): true
isHidden(): false
true
lastModified(): 1970-01-19 05:31:15
length(): 3
mkdir(): false
mkdirs(): false
========上一级目录下的所有文件和路径=========
dir1
dir2
FileTest.txt
file重命名:true
========上一级目录下的所有文件和目录=========
dir1
dir2
FileTest.txt
canRead(): true
setWritable(): true
canWrite(): false
canExecute(): true
========相对路径=========
user.dir:C:\DATA\selfcode
newFile文件是否存在:true
新建newFile文件后是否存在:true, 路径为:C:\DATA\selfcode\test.txt
getName(): test.txt
getParent(): null
getParentFile(): null
getAbsolutePath(): C:\DATA\selfcode\test.txt
getAbsoluteFile(): C:\DATA\selfcode\test.txt
getAbsoluteFile().getParent(): C:\DATA\selfcode
getPath(): test.txt
isAbsolute(): false
getCanonicalPath(): C:\DATA\selfcode\test.txt
getCanonicalFile(): C:\DATA\selfcode\test.txt
URI:file:/C:/DATA/selfcode/test.txt
========系统根目录下的所有文件和路径=========
C:\
getTotalSpace(): 237 G
getFreeSpace(): 41 G
getUsableSpace(): 41 G
Path: C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt

3)结果的一些验证: a)文件长度以及修改时间

如何使用Java中的File類別方法?

b)设置不可写后:

如何使用Java中的File類別方法?

b)磁盘大小

如何使用Java中的File類別方法?

c)user.dir路径

如何使用Java中的File類別方法?

createTempFile临时文件创建示例

1)运行主类

        File file2 = new File("C:\\Users\\LIAOJIANYA\\Desktop\\filetest\\filedir01");
        File tmp01 = file2.createTempFile("tmp01", ".tmp");
        File tmp02 = file2.createTempFile("tmp02", ".tmp", file2);
        tmp02.deleteOnExit();

        File tmp03 = File.createTempFile("tmp03", null);
        System.out.println("tmp01: " + tmp01.getAbsolutePath());
        System.out.println("tmp02: " + tmp02.getAbsolutePath());
        System.out.println("tmp03: " + tmp03.getAbsolutePath());

2)运行结果

tmp01: C:\Users\LIAOJI~1\AppData\Local\Temp\tmp01870328708927314810.tmp
tmp02: C:\Users\LIAOJIANYA\Desktop\filetest\filedir01\tmp023046960943790159256.tmp
tmp03: C:\Users\LIAOJI~1\AppData\Local\Temp\tmp032224782289258299121.tmp

3)查看结果:

a)默认临时文件存放地址:

如何使用Java中的File類別方法?

b)指定临时文件存放地址:

如何使用Java中的File類別方法?

其中,如果需求中需要创建一个临时文件,这个临时文件可能作为存储使用,但在程序运行结束后需要删除文件,可以使用deleteOnExit()方法。

FilenameFilter文件过滤器示例

public String[] list(FilenameFilter filter)方法的使用。 1)运行主类

public class DemoApplication {

    public static void main(String[] args) {
        File file = new File("C:\\Users\\LIAOJIANYA\\Desktop\\filetest\\filedir02\\");
        String[] nameArr = file.list(((dir, name) -> name.endsWith(".doc")));
        for (String name : nameArr) {
            System.out.println(name);
        }   
    }
}

2)运行结果:

文件01.doc

3)验证:

如何使用Java中的File類別方法?

其中,通过使用Lambda表达式,目标类型为FilenameFilter实现文件过滤,上面过滤了以.doc结尾的文件。

以上是如何使用Java中的File類別方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除