Java中File類方法詳解以及實踐
File類概述
File類是java.io包下代表與平臺無關(guān)的文件和目錄。File可以新建、刪除、重命名文件和目錄,但是不能訪問文件內(nèi)容本身,如果需要訪問內(nèi)容的話,需要通過輸入/輸出流進行訪問。
File類可以使用文件路徑字符串創(chuàng)建File實例,路徑既可以是絕對路徑,也可以是相對路徑。一般相對路徑的話是由系統(tǒng)屬性user.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對象鎖表示的文件名或者目錄名(若為目錄,返回的是最后一級子目錄)。
- 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對象所對應的文件或目錄是否可執(zhí)行。
- public boolean exists():判斷此File對象所對應的文件或目錄是否存在。
- public boolean isDirectory():判斷此File對象是否為目錄。
- public boolean isFile():判斷此File對象是否為文件。
- public boolean isHidden():判斷此File對象是否為隱藏。
- public long lastModified():返回該File對象最后修改的時間戳,我們可以通過SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");進行格式化為時間日期展示。
- public boolean setLastModified(long time):設置該File對象最后修改的時間戳。
- public long length():返回該File對象的文件內(nèi)容長度。
- public boolean createNewFile() throws IOException:當此File對象所對應的文件不存在時,該方法會新建一個該File對象所指定的新文件,如果創(chuàng)建成功,返回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關(guān)閉的時候,刪除該文件或者目錄,不像delete()方法一調(diào)用就刪除。一般用于臨時文件比較合適。
- public String[] list():列出File對象的所有子文件名和路徑名,返回的是String數(shù)組。
- public File[] listFiles():列出File對象的所有子文件嗎和路徑名,返回的是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對象所對應的文件或目錄,如果重命名成功,則返回true;否則,返回false。
- public boolean setReadOnly():設置此File對象為只讀權(quán)限。
- public boolean setWritable(boolean writable, boolean ownerOnly):寫權(quán)限設置,writable如果為true,允許寫訪問權(quán)限;如果為false,寫訪問權(quán)限是不允許的。ownerOnly如果為true,則寫訪問權(quán)限僅適用于所有者;否則它適用于所有人。
- public boolean setWritable(boolean writable): 底層實現(xiàn)是:通過setWritable(writable, true)實現(xiàn),默認是僅適用于文件或目錄所有者。
public boolean setWritable(boolean writable) {
return setWritable(writable, true);
}- public boolean setReadable(boolean readable, boolean ownerOnly):讀權(quán)限設置,readable如果為true,允許讀訪問權(quán)限;如果為false,讀訪問權(quán)限是不允許的。ownerOnly如果為true,則讀訪問權(quán)限僅適用于所有者;否則它適用于所有人。
- public boolean setReadable(boolean readable): 底層實現(xiàn)是:通過setReadable(readable, true)實現(xiàn),默認是僅適用于文件或目錄所有者。
public boolean setReadable(boolean readable) {
return setReadable(readable, true);
}- public boolean setExecutable(boolean executable, boolean ownerOnly):執(zhí)行權(quán)限設置,executable如果為true,允許執(zhí)行訪問權(quán)限;如果為false,執(zhí)行訪問權(quán)限是不允許的。ownerOnly如果為true,則執(zhí)行訪問權(quán)限僅適用于所有者;否則它適用于所有人。
- public boolean setExecutable(boolean executable): 底層實現(xiàn)是:通過setExecutable(executable, true)實現(xiàn),默認是僅適用于文件或目錄所有者。
public boolean setExecutable(boolean executable) {
return setExecutable(executable, true);
}- public static File[] listRoots():列出系統(tǒng)所有的根路徑,可以直接通過File類進行調(diào)用。
- public long getTotalSpace():返回總空間大小,默認單位為字節(jié)。
- public long getFreeSpace():Returns the number of unallocated bytes in the partition,返回未被分配空間大小,默認單位為字節(jié)。
- public long getUsableSpace():Returns the number of bytes available to this virtual machine on the partition,返回可用空間大小,默認單位為字節(jié)。
- public Path toPath():返回該File對象的Path對象。
- public static File createTempFile(String prefix, String suffix) throws IOException:在默認存放臨時文件目錄中,創(chuàng)建一個臨時空文件??梢灾苯邮褂肍ile類來調(diào)用,使用給定前綴、系統(tǒng)生成的隨機數(shù)以及給定后綴作為文件名。prefix至少3字節(jié)長。如果suffix設置為null,則默認后綴為.tmp。
- public static File createTempFile(String prefix, String suffix, File directory):在指定的臨時文件目錄directort中,創(chuàng)建一個臨時空文件??梢灾苯邮褂肍ile類來調(diào)用,使用給定前綴、系統(tǒng)生成的隨機數(shù)以及給定后綴作為文件名。prefix至少3字節(jié)長。如果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"這三個數(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("========上一級目錄下的所有文件和路徑=========");
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("========系統(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)運行結(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 ========上一級目錄下的所有文件和路徑========= 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 ========系統(tǒng)根目錄下的所有文件和路徑========= C:\ getTotalSpace(): 237 G getFreeSpace(): 41 G getUsableSpace(): 41 G Path: C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
3)結(jié)果的一些驗證: a)文件長度以及修改時間

b)設置不可寫后:

b)磁盤大小

c)user.dir路徑

createTempFile臨時文件創(chuàng)建示例
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)運行結(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)默認臨時文件存放地址:

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

其中,如果需求中需要創(chuàng)建一個臨時文件,這個臨時文件可能作為存儲使用,但在程序運行結(jié)束后需要刪除文件,可以使用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)運行結(jié)果:
文件01.doc
3)驗證:

其中,通過使用Lambda表達式,目標類型為FilenameFilter實現(xiàn)文件過濾,上面過濾了以.doc結(jié)尾的文件。
總結(jié)
到此這篇關(guān)于Java中File類方法詳解以及實踐的文章就介紹到這了,更多相關(guān)Java File類方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot集成WebSocket實現(xiàn)后臺向前端推送信息的示例
這篇文章主要介紹了SpringBoot集成WebSocket實現(xiàn)后臺向前端推送信息的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12
Spring動態(tài)管理定時任務之ThreadPoolTaskScheduler解讀
這篇文章主要介紹了Spring動態(tài)管理定時任務之ThreadPoolTaskScheduler解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
在SpringMVC框架下實現(xiàn)文件的上傳和下載示例
本篇文章主要介紹了在SpringMVC框架下實現(xiàn)文件的上傳和下載示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-02-02
SpringBoot配置數(shù)據(jù)庫密碼加密的實現(xiàn)
這篇文章主要介紹了SpringBoot配置數(shù)據(jù)庫密碼加密的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03
Spring?MVC如何實現(xiàn)接口Controller定義控制器
這篇文章主要介紹了Spring?MVC如何實現(xiàn)接口Controller定義控制器,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
ImportBeanDefinitionRegistrar手動控制BeanDefinition創(chuàng)建注冊詳解
這篇文章主要為大家介紹了ImportBeanDefinitionRegistrar手動控制BeanDefinition創(chuàng)建注冊詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12

