Spring资源访问与国际化


一、Resource

Resource 是 Spring 资源访问的接口,主要实现类如下:

  • UrlResource:访问网络资源
  • ClassPathResource:访问类路径下资源(resource 文件夹)
  • FileSystemResource:访问文件系统资源

1、UrlResource

try {
    // 获取网络资源, 包括http、file前缀的资源
    UrlResource urlResource = new UrlResource("http://www.baidu.com/");
    // 获取项目根路径下的资源文件 123.txt
    //UrlResource urlResource = new UrlResource("file:123.txt");

    System.out.println(urlResource.getFilename());
    System.out.println(urlResource.getURI());
    System.out.println(urlResource.getURL());
    System.out.println(urlResource.getDescription());

    InputStream inputStream = urlResource.getInputStream();

} catch (Exception e) {
    e.printStackTrace();
}

2、ClassPathResource

获取类路径下资源,resource 资源文件夹下资源

ClassPathResource classPathResource = new ClassPathResource("123.txt");

System.out.println(classPathResource.getFilename());

InputStream inputStream = classPathResource.getInputStream();
byte[] bytes = new byte[1024];
while (inputStream.read(bytes) != -1){
    System.out.println(new String(bytes));
}

3、FileSystemResource

// 绝对路径
String path = "D:\\code_learn\\demo\\demo1\\src\\main\\resources\\123.txt";
// 相对路径, 读取项目根路径下的内容
FileSystemResource fileSystemResource = new FileSystemResource(path);

System.out.println(fileSystemResource.getFilename());

  目录