JavaWeb开发

class.getResource()和class.getCla

2018-05-31  本文已影响1人  坚持到底v2

获取路径的区别如下:
挺乱的!! 总结的也不一定对!!


class.getResource()


App.class.getResource("/").getPath();  
// 输出 /D:/xxx/target/classes/

App.class.getResource("").getPath();  
// 输出  /D:/xxx/target/classes/com/xxx/test/

App.class.getResource("/myFile").getPath();  
// 输出  /D:/xxx/target/classes/myFile , myFile必须是存在的文件或文件夹

App.class.getResource("/..").getPath();  
// 输出 null, 不能获取比根目录还上级的目录

App.class.getResource("../../../../../../..").getPath();  
// 输出 null,不能获取比根目录还上级的目录

new File(App.class.getResource("/").getPath()).getParent(); 
// 输出 /D:/xxx/target/ , 曲线救国


class.getClassLoader().getResource()

在 一般的java main项目中测试结果

在 Servlet 中 测试结果
所有类的classLoader获取的结果都一样!! 直接使用自己的类的classLoader就行


App.class.getClassLoader().getResource("/");   
// 输出 null


App.class.getClassLoader().getResource("").getPath();  
// 输出 /D:/xxx/target/classes/ 
// 等价于 App.class.getResource("/").getPath();  

App.class.getClassLoader().getResource("myFile").getPath();  
// 输出  /D:/xxx/target/classes/myFile , myFile必须是存在的文件或文件夹
// 等价于 App.class.getResource("/myFile").getPath();  


总结:
在jar包中获取自己的jar包内的资源文件的内容要使用 MyClass.class.getResource("/xx")
MyClass.class.getClassLoader().getResource("xx")
在jar包中获取所在项目的资源文件的内容要使用 MyClass.class.getResource("/")
MyClass.class.getClassLoader().getResource("") 然后创建一个File对象,在根据getParent() 等文件函数获取到资源文件路径


打包之后的jar包获取运行时路径

当 jar包 以 java -jar some.jar 运行时,仅仅使用 class.getResource("/")class.getClassLoader().getResource("") 时都是 null
而使用 class.getResource("/xxx") 时返回fileUri,

所以获取运行时路径的有两种方式

    public static void main(String[] args) throws Throwable {
        String runtimePath = getRuntimePath();
        System.out.println("runtimePath1=" + runtimePath);
        File file = new File(runtimePath, "myconfig.json");
        try (FileWriter fileWriter = new FileWriter(file)) {
            fileWriter.write("somestr");
        }
        System.out.println(file.getAbsolutePath() + " content is "
                + MyFileUtils.readFile(file));

        System.out.println();
        System.out.println();

        runtimePath = getRuntimePath2();
        System.out.println("runtimePath2=" + runtimePath);
        file = new File(runtimePath, "myconfig.json");
        try (FileWriter fileWriter = new FileWriter(file)) {
            fileWriter.write("somestr");
        }
        System.out.println(file.getAbsolutePath() + " content is "
                + MyFileUtils.readFile(file));
    }

    /**
     * 获取运行时路径
     */
    public static String getRuntimePath() throws UnsupportedEncodingException {
        URL url = App.class.getProtectionDomain().getCodeSource().getLocation();
        // 转化为utf-8编码
        String filePath = URLDecoder.decode(url.getPath(), "utf-8");
        File file = new File(filePath);
        if (filePath.endsWith(".jar")) {
            // 可执行jar包运行的结果里包含".jar"
            file = file.getParentFile();
        }
        return file.getAbsolutePath();
    }

    /**
     * 获取运行时路径
     * 
     * @throws URISyntaxException
     */
    public static String getRuntimePath2()
            throws UnsupportedEncodingException, URISyntaxException {
        URL url = App.class
                .getResource("/" + App.class.getName().split("[.]", 2)[0]);
        // 转化为utf-8编码
        String filePath = URLDecoder.decode(url.getPath(), "utf-8");
        File file = null;
        try {
            URI fileUri = new URI(filePath);
            file = new File(fileUri);
        } catch (Exception e) {
            file = new File(filePath);
        }
        return file.getParentFile().getParentFile().getAbsolutePath();
    }

上一篇下一篇

猜你喜欢

热点阅读