在Spring Boot中从类路径加载文件的示例
资源加载器
使用Java,您可以使用当前线程的classLoader并尝试加载文件,但是SpringFramework为您提供了更为优雅的解决方案,例如ResourceLoader。
您只需要自动连接ResourceLoader,然后调用getResource(„somePath“)方法即可。
在SpringBoot(WAR)中从资源目录/类路径加载文件的示例
在以下示例中,我们从类路径中加载名为GeoLite2-Country.mmdb的文件作为资源,然后将其作为File对象检索。
@Service("geolocationservice")
publicclassGeoLocationServiceImplimplementsGeoLocationService{
privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(GeoLocationServiceImpl.class);
privatestaticDatabaseReaderreader=null;
privateResourceLoaderresourceLoader;
@Autowired
publicGeoLocationServiceImpl(ResourceLoaderresourceLoader){
this.resourceLoader=resourceLoader;
}@PostConstruct
publicvoidinit(){
try{
LOGGER.info("GeoLocationServiceImpl:TryingtoloadGeoLite2-Countrydatabase...");
Resourceresource=resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");
FiledbAsFile=resource.getFile();//Initializethereader
reader=newDatabaseReader
.Builder(dbAsFile)
.fileMode(Reader.FileMode.MEMORY)
.build();
LOGGER.info("GeoLocationServiceImpl:Databasewasloadedsuccessfully.");
}catch(IOException|NullPointerExceptione){
LOGGER.error("Databasereadercoundnotbeinitialized.",e);
}
}
@PreDestroy
publicvoidpreDestroy(){
if(reader!=null){
try{
reader.close();
}catch(IOExceptione){
LOGGER.error("Failedtoclosethereader.");
}
}
}
}
在SpringBoot(JAR)中从资源目录/类路径加载文件的示例
如果您想从SpringBootJAR中的classpath加载文件,则必须使用该resource.getInputStream()方法将其作为InputStream检索。如果尝试使用resource.getFile()该方法,则会收到错误消息,因为Spring尝试访问文件系统路径,但无法访问JAR中的路径。
@Service("geolocationservice")
publicclassGeoLocationServiceImplimplementsGeoLocationService{
privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(GeoLocationServiceImpl.class);
privatestaticDatabaseReaderreader=null;
privateResourceLoaderresourceLoader;
@Inject
publicGeoLocationServiceImpl(ResourceLoaderresourceLoader){
this.resourceLoader=resourceLoader;
}@PostConstruct
publicvoidinit(){
try{
LOGGER.info("GeoLocationServiceImpl:TryingtoloadGeoLite2-Countrydatabase...");
Resourceresource=resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");
InputStreamdbAsStream=resource.getInputStream();//<--thisisthedifference
//Initializethereader
reader=newDatabaseReader
.Builder(dbAsStream)
.fileMode(Reader.FileMode.MEMORY)
.build();
LOGGER.info("GeoLocationServiceImpl:Databasewasloadedsuccessfully.");
}catch(IOException|NullPointerExceptione){
LOGGER.error("Databasereadercoundnotbeinitialized.",e);
}
}
@PreDestroy
publicvoidpreDestroy(){
if(reader!=null){
try{
reader.close();
}catch(IOExceptione){
LOGGER.error("Failedtoclosethereader.");
}
}
}
}
以上就是在SpringBoot中从类路径加载文件的示例的详细内容,更多关于springboot加载文件的资料请关注毛票票其它相关文章!