Spring Boot - Reading Text File using ResourceLoader

后端 未结 5 1394
生来不讨喜
生来不讨喜 2020-12-03 05:30

I’m trying to read a text file using Spring resource loader like this :

Resource resource  = resourceLoader.getResource(\"classpath:\\\\static\\\\Sample.txt\         


        
5条回答
  •  無奈伤痛
    2020-12-03 06:24

    I had the same problem and as @Gipple Lake explained, with Spring boot you need to load file as inputStream. So bellow I'll add my code as example, where I want to read import.xml file

    public void init() {
        Resource resource = new ClassPathResource("imports/imports.xml");
        try {
            InputStream dbAsStream = resource.getInputStream();
            try {
                document = readXml(dbAsStream);
                } catch (SAXException e) {
                    trace.error(e.getMessage(), e);
                    e.printStackTrace();
                } catch (ParserConfigurationException e) {
                    trace.error(e.getMessage(), e);
                    e.printStackTrace();
                }
        } catch (IOException e) {
            trace.error(e.getMessage(), e);
            e.printStackTrace();
        }
        initListeImports();
        initNewImports();
    }
    
    public static Document readXml(InputStream is) throws SAXException, IOException,
          ParserConfigurationException {
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    
          dbf.setValidating(false);
          dbf.setIgnoringComments(false);
          dbf.setIgnoringElementContentWhitespace(true);
          dbf.setNamespaceAware(true);
          DocumentBuilder db = null;
          db = dbf.newDocumentBuilder();
    
          return db.parse(is);
      }
    

    I added "imports.xml" bellow src/main/ressources/imports

提交回复
热议问题