RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
在SpringBoot中实现从类路径加载文件-创新互联

本篇文章为大家展示了在Spring Boot中实现从类路径加载文件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

站在用户的角度思考问题,与客户深入沟通,找到商河网站设计与商河网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:做网站、成都网站设计、企业官网、英文网站、手机端网站、网站推广、空间域名、雅安服务器托管、企业邮箱。业务覆盖商河地区。

资源加载器

使用Java,您可以使用当前线程的classLoader并尝试加载文件,但是Spring Framework为您提供了更为优雅的解决方案,例如ResourceLoader。

您只需要自动连接ResourceLoader,然后调用getResource(„somePath“)方法即可。

在Spring Boot(WAR)中从资源目录/类路径加载文件的示例

在以下示例中,我们从类路径中加载名为GeoLite2-Country.mmdb的文件作为资源,然后将其作为File对象检索。

@Service("geolocationservice") 
public class GeoLocationServiceImpl implements GeoLocationService { 
  private static final Logger LOGGER = LoggerFactory.getLogger(GeoLocationServiceImpl.class); 
  private static DatabaseReader reader = null; 
  private ResourceLoader resourceLoader; 
  @Autowired 
  public GeoLocationServiceImpl(ResourceLoader resourceLoader) { 
    this.resourceLoader = resourceLoader; 
  }  @PostConstruct 
  public void init() { 
    try { 
      LOGGER.info("GeoLocationServiceImpl: Trying to load GeoLite2-Country database..."); 
      Resource resource = resourceLoader.getResource("classpath:GeoLite2-Country.mmdb"); 
      File dbAsFile = resource.getFile();      // Initialize the reader 
      reader = new DatabaseReader 
            .Builder(dbAsFile) 
            .fileMode(Reader.FileMode.MEMORY) 
            .build(); 
      LOGGER.info("GeoLocationServiceImpl: Database was loaded successfully."); 
    } catch (IOException | NullPointerException e) { 
      LOGGER.error("Database reader cound not be initialized. ", e); 
    } 
  } 
  @PreDestroy 
  public void preDestroy() { 
    if (reader != null) { 
      try { 
        reader.close(); 
      } catch (IOException e) { 
        LOGGER.error("Failed to close the reader."); 
      } 
    } 
  } 
} 

名称栏目:在SpringBoot中实现从类路径加载文件-创新互联
文章转载:http://cqwzjz.cn/article/gpgds.html