java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java获取路径方式

Java获取路径的6种方式代码示例

作者:西洼工作室

在Java中获取路径的方法有多种,每种方法适用于不同的场景,这篇文章主要介绍了Java获取路径的6种方式,文中通过代码介绍的非常详细,需要的朋友可以参考下

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 类
         */
        // 创建一个File对象
        File file = new File("example.txt");

        // 获取绝对路径
        String absolutePath = file.getAbsolutePath();
        System.out.println("Absolute Path: " + absolutePath);

        // 获取相对路径(相对于当前工作目录)
        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及以上)
         */
        // 获取当前工作目录
        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. 获取当前执行文件的路径(Java应用)
         */
        String path = Demo1.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        System.out.println("Executable Path: " + path);
    }
}

总结

到此这篇关于Java获取路径的6种方式的文章就介绍到这了,更多相关Java获取路径方式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文