Java读取资料文件相关类方法


前言

学习过程中一些不知道的类和方法的记录


一、Spring之ClassPathResource

ClassPathResource是用于Spring中加载资源文件的类

1.引入库

代码如下(示例):

import org.springframework.core.io.ClassPathResource;

2.读取资源文件

代码如下(示例):

@Test
public void testClassPathResource() throws IOException {
   
     Resource res = new ClassPathResource("resource/ApplicationContext.xml");
     InputStream input = res.getInputStream();
     Assert.assertNotNull(input);
}

3.源码解读

内部源码:

public ClassPathResource(String path) {
   
     this(path, (ClassLoader) null);
 }
public ClassPathResource(String path, ClassLoader classLoader) {
   
    Assert.notNull(path, "Path must not be null");
    String pathToUse = StringUtils.cleanPath(path);
    if (pathToUse.startsWith("/")) {
   
        pathToUse = pathToUse.substring(1);
    }
    this.path = pathToUse;
    this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}
public ClassPathResource(String path, Class<?> clazz) {
   
     Assert.notNull(path, "Path must not be null");
     this.path = StringUtils.cleanPath(path);
     this.clazz = clazz;
}

/**
 * 读取资源文件
 * This implementation opens an InputStream for the given class path resource.
 * @see java.lang.ClassLoader#getResourceAsStream(String)
 * @see java.lang.Class#getResourceAsStream(String)
 */
@Override
public InputStream getInputStream() throws IOException {
   
    InputStream is;
    if (this.clazz != null) {
   
        is = this.clazz.getResourceAsStream(this.path);
    }
    else if (this.classLoader != null) {
   
        is = this.classLoader.getResourceAsStream(this.path);
    }
    else {
   
        is = ClassLoader.getSystemResourceAsStream(this.path);
    }
    if (is == null) {
   
        throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
    }
    return is;
}

该类获取资源文件有两种方法:通过class获取和classLoader获取

@Test
public void testResouce() {
   
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    System.out.println(loader.getResource("").getPath());

    System.out.println(this.getClass().getResource("").getPath());
    System.out.println(this.getClass().getResource("/").getPath());

    System.out.println(System.getProperty("user.dir"));
}

输出结果:

/home
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值