溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java中File類方法怎么用

發(fā)布時(shí)間:2022-04-08 16:43:42 來源:億速云 閱讀:122 作者:iii 欄目:開發(fā)技術(shù)

今天小編給大家分享一下Java中File類方法怎么用的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

File類概述

File類是java.io包下代表與平臺(tái)無關(guān)的文件和目錄。File可以新建、刪除、重命名文件和目錄,但是不能訪問文件內(nèi)容本身,如果需要訪問內(nèi)容的話,需要通過輸入/輸出流進(jìn)行訪問。

File類可以使用文件路徑字符串創(chuàng)建File實(shí)例,路徑既可以是絕對(duì)路徑,也可以是相對(duì)路徑。一般相對(duì)路徑的話是由系統(tǒng)屬性u(píng)ser.dir指定,即為Java VM所在路徑。

File類常用構(gòu)造器

    /**
     * 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對(duì)象鎖表示的文件名或者目錄名(若為目錄,返回的是最后一級(jí)子目錄)。

  • public String getParent():返回此File對(duì)象所對(duì)應(yīng)的路徑名,返回String類型。

  • public File getParentFile():返回此File對(duì)象的父目錄,返回File類型。

  • public String getPath():返回此File對(duì)象所對(duì)應(yīng)的路徑名,返回String類型。

  • public boolean isAbsolute():判斷File對(duì)象所對(duì)應(yīng)的文件或者目錄是否是絕對(duì)路徑。

  • public String getAbsolutePath():返回此File對(duì)象所對(duì)應(yīng)的絕對(duì)路徑,返回String類型。

  • public String getCanonicalPath() throws IOException:

  • public File getCanonicalFile() throws IOException:

  • public File getAbsoluteFile():返回此File對(duì)象所對(duì)應(yīng)的絕對(duì)路徑,返回File類型。

  • public boolean canRead():判斷此File對(duì)象所對(duì)應(yīng)的文件或目錄是否可讀。

  • public boolean canWrite():判斷此File對(duì)象所對(duì)應(yīng)的文件或目錄是否可寫。

  • public boolean canExecute():判斷此File對(duì)象所對(duì)應(yīng)的文件或目錄是否可執(zhí)行。

  • public boolean exists():判斷此File對(duì)象所對(duì)應(yīng)的文件或目錄是否存在。

  • public boolean isDirectory():判斷此File對(duì)象是否為目錄。

  • public boolean isFile():判斷此File對(duì)象是否為文件。

  • public boolean isHidden():判斷此File對(duì)象是否為隱藏。

  • public long lastModified():返回該File對(duì)象最后修改的時(shí)間戳,我們可以通過SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");進(jìn)行格式化為時(shí)間日期展示。

  • public boolean setLastModified(long time):設(shè)置該File對(duì)象最后修改的時(shí)間戳。

  • public long length():返回該File對(duì)象的文件內(nèi)容長度。

  • public boolean createNewFile() throws IOException:當(dāng)此File對(duì)象所對(duì)應(yīng)的文件不存在時(shí),該方法會(huì)新建一個(gè)該File對(duì)象所指定的新文件,如果創(chuàng)建成功,返回true;否則,返回false。

  • public boolean delete():刪除File對(duì)象所對(duì)應(yīng)的文件或目錄,刪除成功,返回true;否則,返回false。

  • public void deleteOnExit():Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.意思就是在VM關(guān)閉的時(shí)候,刪除該文件或者目錄,不像delete()方法一調(diào)用就刪除。一般用于臨時(shí)文件比較合適。

  • public String[] list():列出File對(duì)象的所有子文件名和路徑名,返回的是String數(shù)組。

  • public File[] listFiles():列出File對(duì)象的所有子文件嗎和路徑名,返回的是File數(shù)組。

  • public boolean mkdir():創(chuàng)建目錄,并且只能在已有的父類下面創(chuàng)建子類,如果父類沒有,那么就無法創(chuàng)建子類。

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

  • public boolean renameTo(File dest):重命名此File對(duì)象所對(duì)應(yīng)的文件或目錄,如果重命名成功,則返回true;否則,返回false。

  • public boolean setReadOnly():設(shè)置此File對(duì)象為只讀權(quán)限。

  • public boolean setWritable(boolean writable, boolean ownerOnly):寫權(quán)限設(shè)置,writable如果為true,允許寫訪問權(quán)限;如果為false,寫訪問權(quán)限是不允許的。ownerOnly如果為true,則寫訪問權(quán)限僅適用于所有者;否則它適用于所有人。

  • public boolean setWritable(boolean writable): 底層實(shí)現(xiàn)是:通過setWritable(writable, true)實(shí)現(xiàn),默認(rèn)是僅適用于文件或目錄所有者。

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

  • public boolean setReadable(boolean readable): 底層實(shí)現(xiàn)是:通過setReadable(readable, true)實(shí)現(xiàn),默認(rèn)是僅適用于文件或目錄所有者。

    public boolean setReadable(boolean readable) {
        return setReadable(readable, true);
    }
  • public boolean setExecutable(boolean executable, boolean ownerOnly):執(zhí)行權(quán)限設(shè)置,executable如果為true,允許執(zhí)行訪問權(quán)限;如果為false,執(zhí)行訪問權(quán)限是不允許的。ownerOnly如果為true,則執(zhí)行訪問權(quán)限僅適用于所有者;否則它適用于所有人。

  • public boolean setExecutable(boolean executable): 底層實(shí)現(xiàn)是:通過setExecutable(executable, true)實(shí)現(xiàn),默認(rèn)是僅適用于文件或目錄所有者。

    public boolean setExecutable(boolean executable) {
        return setExecutable(executable, true);
    }
  • public static File[] listRoots():列出系統(tǒng)所有的根路徑,可以直接通過File類進(jìn)行調(diào)用。

  • public long getTotalSpace():返回總空間大小,默認(rèn)單位為字節(jié)。

  • public long getFreeSpace():Returns the number of unallocated bytes in the partition,返回未被分配空間大小,默認(rèn)單位為字節(jié)。

  • public long getUsableSpace():Returns the number of bytes available to this virtual machine on the partition,返回可用空間大小,默認(rèn)單位為字節(jié)。

  • public Path toPath():返回該File對(duì)象的Path對(duì)象。

  • public static File createTempFile(String prefix, String suffix) throws IOException:在默認(rèn)存放臨時(shí)文件目錄中,創(chuàng)建一個(gè)臨時(shí)空文件??梢灾苯邮褂肍ile類來調(diào)用,使用給定前綴、系統(tǒng)生成的隨機(jī)數(shù)以及給定后綴作為文件名。prefix至少3字節(jié)長。如果suffix設(shè)置為null,則默認(rèn)后綴為.tmp。

  • public static File createTempFile(String prefix, String suffix, File directory):在指定的臨時(shí)文件目錄directort中,創(chuàng)建一個(gè)臨時(shí)空文件??梢灾苯邮褂肍ile類來調(diào)用,使用給定前綴、系統(tǒng)生成的隨機(jī)數(shù)以及給定后綴作為文件名。prefix至少3字節(jié)長。如果suffix設(shè)置為null,則默認(rèn)后綴為.tmp。

常用方法示例

1)運(yùn)行主類

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"這三個(gè)數(shù)字
        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("========上一級(jí)目錄下的所有文件和路徑=========");
        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("========上一級(jí)目錄下的所有文件和目錄=========");
        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("========相對(duì)路徑=========");
        //默認(rèn)相對(duì)路徑是user.dir即為當(dāng)前工程所在位置
        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("========系統(tǒng)根目錄下的所有文件和路徑=========");
        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)運(yùn)行結(jié)果:

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
========上一級(jí)目錄下的所有文件和路徑=========
dir1
dir2
FileTest.txt
file重命名:true
========上一級(jí)目錄下的所有文件和目錄=========
dir1
dir2
FileTest.txt
canRead(): true
setWritable(): true
canWrite(): false
canExecute(): true
========相對(duì)路徑=========
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
========系統(tǒng)根目錄下的所有文件和路徑=========
C:\
getTotalSpace(): 237 G
getFreeSpace(): 41 G
getUsableSpace(): 41 G
Path: C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt

3)結(jié)果的一些驗(yàn)證: a)文件長度以及修改時(shí)間

Java中File類方法怎么用

b)設(shè)置不可寫后:

Java中File類方法怎么用

b)磁盤大小

Java中File類方法怎么用

c)user.dir路徑

Java中File類方法怎么用

createTempFile臨時(shí)文件創(chuàng)建示例

1)運(yùn)行主類

        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)運(yùn)行結(jié)果

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)查看結(jié)果:

a)默認(rèn)臨時(shí)文件存放地址:

Java中File類方法怎么用

b)指定臨時(shí)文件存放地址:

Java中File類方法怎么用

其中,如果需求中需要?jiǎng)?chuàng)建一個(gè)臨時(shí)文件,這個(gè)臨時(shí)文件可能作為存儲(chǔ)使用,但在程序運(yùn)行結(jié)束后需要?jiǎng)h除文件,可以使用deleteOnExit()方法。

FilenameFilter文件過濾器示例

public String[] list(FilenameFilter filter)方法的使用。 1)運(yùn)行主類

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)運(yùn)行結(jié)果:

文件01.doc

3)驗(yàn)證:

Java中File類方法怎么用

其中,通過使用Lambda表達(dá)式,目標(biāo)類型為FilenameFilter實(shí)現(xiàn)文件過濾,上面過濾了以.doc結(jié)尾的文件。

以上就是“Java中File類方法怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI