Reading In A File With Java

Here’s a short code example demonstrating how to read in a file within your application. This snippet assumes the file data.json is within your application’s root directory (change as necessary). The contents of the file are read into the variable json – insert your own processing code after the while code block. If the file cannot be found, or if there are other difficulties in reading from the file, an IOException will be thrown.

try {
    InputStream is = context.getResourceAsStream("/data.json");
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));  
    String json = "";
    String line = "";   
    while (line != null) {
        json += line;
        line = reader.readLine();
    }   
    //Do something with the read-in data within the json variable.
}
catch (IOException e) {
    throw new RuntimeException("Unable to read in file.");
}