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