springboot打包后获取resources下的静态文件

springboot打包后是无法直接访问resources下的文件,必须通过ResourceLoader进行获取
例如读取csv文件。

//读取csv配对文件,初始化映射关系
        File csvFile = null;
        InputStream stream = null;
        InputStreamReader reader = null;
        try {
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            //读取csv文件
            stream = resourceLoader.getResource("classpath:bayonet-pair.csv").getInputStream();  //文件名  
            reader = new InputStreamReader(stream, "GBK");
            CSVParser parser = CSVFormat.DEFAULT.parse(reader);
            Iterator<CSVRecord> iterator = parser.iterator();
            iterator.next(); //跳过第一行
            CSVRecord item;
            while (iterator.hasNext()){
                item = iterator.next();
				//略
            }
        } catch (IndexOutOfBoundsException e) {
            log.error("严重!!请检查csv文件是否存在空白数据!空白数据请用‘*’号代替",e);
        }catch (Exception e) {
            log.error("严重!!读取CSV配对文件时发生异常",e);
        }finally {
            if(reader != null){
                reader.close();
            }
            if(stream != null){
                stream.close();
            }
        }
        log.info("启动初始化完成.");
    }

你可能感兴趣的:(基础知识)