Read file

By | May 23, 2016

Old School :

        StringBuilder result = new StringBuilder();
        String path = getClass().getClassLoader().getResource("product-info.json").getPath();
        try {
            String urlDecode = URLDecoder.decode(path, "utf-8");
            File file = new File(urlDecode);
            Scanner scanner = new Scanner(file);
            while (scanner.hasNext()) {
                result.append(scanner.nextLine());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(result);}

Using library IOUtils :

        <dependency>
            <groupId>org.apache.directory.studio</groupId>
            <artifactId>org.apache.commons.io</artifactId>
            <version>2.4</version>
        </dependency>
        String result = "";
        ClassLoader classLoader = getClass().getClassLoader();
        try {
            result = IOUtils.toString(classLoader.getResourceAsStream("product-info.json"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);