欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java獲取路徑的6種方式代碼示例

 更新時(shí)間:2025年02月19日 09:38:45   作者:西洼工作室  
在Java中獲取路徑的方法有多種,每種方法適用于不同的場(chǎng)景,這篇文章主要介紹了Java獲取路徑的6種方式,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下

public class Demo1 {
    public static void main(String[] args) {
        /*
        1.使用 System 屬性
         */
        // 獲取用戶的主目錄
        String userHome = System.getProperty("user.home");
        System.out.println("User Home: " + userHome);

        // 獲取Java的安裝目錄
        String javaHome = System.getProperty("java.home");
        System.out.println("Java Home: " + javaHome);

        /*
         * 2.使用 ClassLoader 獲取資源路徑
         */
        // 獲取類路徑下的資源文件路徑
        ClassLoader classLoader = Demo1.class.getClassLoader();
        URL resourceUrl = classLoader.getResource("config.properties");
        String resourcePath = resourceUrl != null ? resourceUrl.getPath() : null;
        System.out.println("Resource Path: " + resourcePath);

        /*
        3.使用 File 類
         */
        // 創(chuàng)建一個(gè)File對(duì)象
        File file = new File("example.txt");

        // 獲取絕對(duì)路徑
        String absolutePath = file.getAbsolutePath();
        System.out.println("Absolute Path: " + absolutePath);

        // 獲取相對(duì)路徑(相對(duì)于當(dāng)前工作目錄)
        String canonicalPath;
        try {
            canonicalPath = file.getCanonicalPath();
            System.out.println("Canonical Path: " + canonicalPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 獲取父目錄路徑
        String parentPath = file.getParent();
        System.out.println("Parent Path: " + parentPath);


        /*
        4.使用 Paths 類(Java 7及以上)
         */
        // 獲取當(dāng)前工作目錄
        Path currentDir = Paths.get(".").toAbsolutePath();
        System.out.println("Current Directory: " + currentDir);

        // 拼接路徑
        Path filePath = Paths.get(currentDir.toString(), "example.txt");
        System.out.println("File Path: " + filePath);

        /*
        5.使用 URI
         */
        File file2 = new File("example.txt");
        URI uri = file2.toURI();
        String uriPath = uri.getPath();
        System.out.println("URI Path: " + uriPath);

        /*
        6. 獲取當(dāng)前執(zhí)行文件的路徑(Java應(yīng)用)
         */
        String path = Demo1.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        System.out.println("Executable Path: " + path);
    }
}

總結(jié)

到此這篇關(guān)于Java獲取路徑的6種方式的文章就介紹到這了,更多相關(guān)Java獲取路徑方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論