'Reading from a file but getting null in java

I want to read from a file and store it in a string.

This is my method:

public static String createJsonFileFromNode(String filename, JsonNode root)  {
    String dirName = "src/test/resources/json/";
    File dir = new File (dirName);
    File actualFile = new File (dir, filename);
    try (Writer writer = new BufferedWriter(new OutputStreamWriter (
            new FileOutputStream(actualFile), "utf-8")))
    {
        writer.write(String.valueOf(root));
        log.info(actualFile.getPath());
        String updatedJson = FileUtils.readFileToString(actualFile, "UTF-8");
        return updatedJson;
    }
    catch (UnsupportedEncodingException e) {
         e.printStackTrace();
         return "";
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return "";
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}

I have two problems in the above method:

  1. In String dirName = "src/test/resources/json/" I am passing an entire path, which I dont want to. I want to pass it as "/json/"
  2. updatedJson is retuning null even though the file is getting saved to the particular direction. Not sure what is going on. Can someone please help me?

Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source