ApplicationContext获取资源以及环境变量

  • 获取资源方式

1.由于ApplicationContext继承了ResourceLoader接口,所有可通过getResource方法来获取资源。

      Resource resource = parent.getResource("aaa.txt");
        InputStream inputStream = resource.getInputStream();
        System.out.println("resource.contentLength() = " + resource.contentLength());
        FileOutputStream fos = new FileOutputStream("baidu.html");
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        fos.write(bytes,0,bytes.length);

getResource方法十分强大,这里的资源可以是磁盘上的资源,网络上的资源,还可以是classpath下的资源。

2.除此之外,还可以通过特定的一些类来获取指定资源

     //获取classpath下的资源
        ClassPathResource rs = new ClassPathResource("com/springgj");
        File file = rs.getFile();
        printFile(file);

        //获取文件系统资源
        FileSystemResource fs = new FileSystemResource("C:\\Users\\Administrator\\Desktop\\4317.docx");
        System.out.println(fs.contentLength());

        //获取网络资源
        UrlResource urlResource = new UrlResource("https://www.baidu.com");
        System.out.println(urlResource.contentLength());
  • 获取环境变量方式
        System.out.println(environment.getSystemProperties());//获取jvm环境变量
        System.out.println("====");
        System.out.println(environment.getSystemEnvironment());//获取系统环境变量

        //尝试获取classpath
        System.out.println(environment.getSystemProperties().get("java.class.path"));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值