java.nio.file.Path for a classpath resource

后端 未结 8 979
自闭症患者
自闭症患者 2020-11-28 02:55

Is there an API to get a classpath resource (e.g. what I\'d get from Class.getResource(String)) as a java.nio.file.Path? Ideally, I\'d like to use the fancy new Path<

8条回答
  •  粉色の甜心
    2020-11-28 03:45

    Read a File from resources folder using NIO, in java8

    public static String read(String fileName) {
    
            Path path;
            StringBuilder data = new StringBuilder();
            Stream lines = null;
            try {
                path = Paths.get(Thread.currentThread().getContextClassLoader().getResource(fileName).toURI());
                lines = Files.lines(path);
            } catch (URISyntaxException | IOException e) {
                logger.error("Error in reading propertied file " + e);
                throw new RuntimeException(e);
            }
    
            lines.forEach(line -> data.append(line));
            lines.close();
            return data.toString();
        }
    

提交回复
热议问题