0

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.

9
  • 2
    src/test/resources/json/ is not an absolute path. Commented Feb 21, 2022 at 9:21
  • @khelwood I want to pass it as "/json/". Updated the question Commented Feb 21, 2022 at 9:22
  • Does this answer your question? Reading a plain text file in Java Commented Feb 21, 2022 at 9:24
  • @khelwood So what? Filenames don't need to be absolute. Commented Feb 21, 2022 at 9:37
  • 1. The src directory won't be there at runtime. 2. Resources are not files. 3. You can't overwrite resources. Commented Feb 21, 2022 at 9:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.