Java中如何獲取文件的上級(jí)目錄
Java獲取文件的上級(jí)目錄
通過 File 對(duì)象的 getParent 方法即可實(shí)現(xiàn)
// 通過 System.getProperty("user.dir") 方式獲取到項(xiàng)目根目錄 String projectRootDirectoryPath = System.getProperty("user.dir"); System.out.println("當(dāng)前項(xiàng)目根目錄為:\t" + projectRootDirectoryPath); // 通過 File 對(duì)象的 getParent() 方法獲取到根目錄的上級(jí)目錄 String parentPath = new File(projectRootDirectoryPath).getParent(); System.out.println("當(dāng)前項(xiàng)目根目錄的上級(jí)目錄為:\t" + parentPath);
效果截圖
獲取文件的父目錄名稱和父目錄絕對(duì)地址
獲取文件的父目錄名稱
import java.io.File; ? public class Main { ? ? public static void main(String[] args) { ? ? ?? ?//創(chuàng)建file對(duì)象 ? ? ? ? File file = new File("C:/File/demo.txt"); ? ? ? ? //先獲取file的父文件,再getName ? ? ? ? String strParentDirectory = file.getParentFile().getName(); ? ? ? ? System.out.println("文件的上級(jí)目錄為 : " + strParentDirectory); ? ? } }
輸出結(jié)果:
File
獲取文件的父目錄絕對(duì)地址
import java.io.File; ? public class Main { ? ? public static void main(String[] args) { ? ? ?? ?//創(chuàng)建file對(duì)象 ? ? ? ? File file = new File("C:/File/demo.txt"); ? ? ? ? //先獲取file的父文件,再getName ? ? ? ? String strParentDirectory = file.getParentFile().getName(); ? ? ? ? System.out.println("文件的上級(jí)目錄為 : " + strParentDirectory); ? ? } }
輸出結(jié)果:
C:/File
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決IDEA上循環(huán)依賴報(bào)錯(cuò)問題Error:java: Annotation processing&n
這篇文章主要介紹了解決IDEA上循環(huán)依賴報(bào)錯(cuò)問題Error:java: Annotation processing is not supported for module cycles,具有很好的參考價(jià)值,希望對(duì)大家有所幫助2023-10-10如何在Spring Boot應(yīng)用程序中配置了兩個(gè)不同的SOAP Web服務(wù)端點(diǎn)
這篇文章主要介紹了如何在Spring Boot應(yīng)用程序中配置了兩個(gè)不同的SOAP Web服務(wù)端點(diǎn),本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08java對(duì)象對(duì)比之comparable和comparator的區(qū)別
今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識(shí),文章圍繞著comparable和comparator的區(qū)別展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06MyBatis-Plus?updateById更新不了空字符串或null的解決方法
本文主要介紹了MyBatis-Plus?updateById更新不了空字符串或null的解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03@Scheduled 如何讀取動(dòng)態(tài)配置文件
這篇文章主要介紹了@Scheduled 如何讀取動(dòng)態(tài)配置文件的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06Java設(shè)計(jì)模式之建造者模式(Builder模式)介紹
這篇文章主要介紹了Java設(shè)計(jì)模式之建造者模式(Builder模式)介紹,本文講解了為何使用建造者模式、如何使用建造者模式、Builder模式的應(yīng)用等內(nèi)容,需要的朋友可以參考下2015-03-03