-1

I have this code which load the File from class path a=its text file and i want to read it to string what im using is :

 File file = new File(classLoader.getResource("sample.json").getFile());

i don't want to use:

file.getAbsolutePath();

how can i read this text file into String ?

UPDATE i found the solution , what do you think?

 ClassLoader classLoader = getClass().getClassLoader();
is = classLoader.getResourceAsStream("sample.json");
String txt = IOUtils.toString(is);
user63898
  • 29,839
  • 85
  • 272
  • 514

2 Answers2

2

If you're using Java 8, you can use this for reading lines from a file:

List<String> lines = Files.readallLines(file.toPath());

Refer to the docs below:

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-

https://docs.oracle.com/javase/8/docs/api/java/io/File.html#toPath--

EDIT:

For reading from a resource you got as an inputstream, you can use a combination of BufferedReader and InputStreamReader:

String getText() throws IOException{
    StringBuilder txt = new StringBuilder();
    InputStream res = getClass().getClassLoader().getResourceAsStream("sample.json");
    try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) {
        String sCurrentLine;
        while ((sCurrentLine = br.readLine()) != null) {
            txt.append(sCurrentLine + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return txt.toString();
}

Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31
0

You can use the following code to read the file object.

public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(file)) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Amit Gujarathi
  • 1,090
  • 1
  • 12
  • 25