Spring 3.0 inject files as resources

后端 未结 5 1390
星月不相逢
星月不相逢 2020-12-15 15:27

In my Spring 3.0 app, I have some resources in /WEB-INF/dir. At runtime I need some of them as an InputStream (or some other type). How can I retri

5条回答
  •  臣服心动
    2020-12-15 16:09

    Here's a full example to retrieve a classpath resource. I use it to grab SQL files that have really complex queries which I don't want to store in Java classes:

    public String getSqlFileContents(String fileName) {
        StringBuffer sb = new StringBuffer();
        try {
            Resource resource = new ClassPathResource(fileName);
            DataInputStream in = new DataInputStream(resource.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                sb.append(" " + strLine);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    

提交回复
热议问题