java怎么获取资源路径

51次阅读
没有评论

共计 929 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 中,可以使用 ClassLoader 类的 getResource() 方法来获取资源路径。getResource()方法会返回一个 URL 对象,可以使用 URL 对象的 getPath() 方法获取资源的路径。

下面是一个示例代码,演示如何获取资源路径:

public class ResourcePathExample {public static void main(String[] args) {// 获取资源路径
        String resourcePath = ResourcePathExample.class.getClassLoader().getResource("example.txt").getPath();
        System.out.println("Resource Path: " + resourcePath);
    }
}

上述代码中,假设项目中存在一个名为 example.txt 的资源文件。getResource()方法的参数用于指定要获取的资源文件,可以是相对路径或绝对路径。

注意:在使用 getPath() 方法获取路径时,如果路径中存在空格或特殊字符,可能会被编码为 URL 编码形式。如果需要获取原始路径,可以使用 URLDecoder 类进行解码。例如:

import java.net.URLDecoder;

public class ResourcePathExample {public static void main(String[] args) {// 获取资源路径
        String resourcePath = ResourcePathExample.class.getClassLoader().getResource("example%20file.txt").getPath();
        String decodedPath = URLDecoder.decode(resourcePath, "UTF-8");
        System.out.println("Resource Path: " + decodedPath);
    }
}

在上述代码中,资源文件名为 example file.txt,被编码为example%20file.txt。使用URLDecoder.decode() 方法将路径解码为原始路径。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-12发表,共计929字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)