I’m trying to read a text file using Spring resource loader like this :
Resource resource = resourceLoader.getResource(\"classpath:\\\\static\\\\Sample.txt\
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