ResourcesUtils - JiyangM/spring GitHub Wiki

spring 提供了一个用于资源定位的工具类。

我们可以在开发中使用该类获取相关资源。

public static void main(String[] args) throws Exception {
        System.out.println("======== Resource Utils 实现类 ========");

        System.out.println(ResourceUtils.isUrl("classpath:bootstrap.yml"));
        System.out.println(ResourceUtils.isUrl("file:bootstrap.yml"));
        System.out.println(ResourceUtils.isFileURL(new URL("file:/D:/work/project/boot/target/classes/bootstrap.ym")));
        System.out.println(ResourceUtils.getURL("classpath:bootstrap.yml"));

        File file = ResourceUtils.getFile(ResourceUtils.getURL("classpath:bootstrap.yml"));
        System.out.println(file.exists() + "," + file.getAbsolutePath() + "," + file.getName());

        File file1 = ResourceUtils.getFile("classpath:bootstrap.yml");
        System.out.println(file1.exists() + "," + file1.getAbsolutePath() + "," + file1.getName());

        System.out.println("======== Resource 具体实现类 ========");

        ClassPathResource classPathResource = new ClassPathResource("bootstrap.yml");
        File file2 = classPathResource.getFile();
        System.out.println(classPathResource.getClassLoader());
        System.out.println(file2.exists() + "," + file2.getAbsolutePath() + "," + file2.getName());

        FileSystemResource fileSystemResource = new FileSystemResource("D:/work/project/boot/target/classes/bootstrap.yml");
        File file3 = fileSystemResource.getFile();
        System.out.println(fileSystemResource.getPath());
        System.out.println(file3.exists() + "," + file3.getAbsolutePath() + "," + file3.getName());

        InputStreamResource inputStreamResource = new InputStreamResource(new FileInputStream(file3));
        System.out.println(inputStreamResource.exists());
    }
======== Resource Utils 实现类 ========
true
true
true
file:/D:/work/project/boot/target/classes/bootstrap.yml
true,D:\work\project\boot\target\classes\bootstrap.yml,bootstrap.yml
true,D:\work\project\boot\target\classes\bootstrap.yml,bootstrap.yml
======== Resource 具体实现类 ========
sun.misc.Launcher$AppClassLoader@18b4aac2
true,D:\work\project\boot\target\classes\bootstrap.yml,bootstrap.yml
D:/work/project/boot/target/classes/bootstrap.yml
true,D:\work\project\boot\target\classes\bootstrap.yml,bootstrap.yml
true