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.

Rumi
  • 61
  • 1
  • 9
  • 2
    `src/test/resources/json/` is not an absolute path. – khelwood Feb 21 '22 at 09:21
  • @khelwood I want to pass it as "/json/". Updated the question – Rumi Feb 21 '22 at 09:22
  • Does this answer your question? [Reading a plain text file in Java](https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java) – pringi Feb 21 '22 at 09:24
  • @khelwood So what? Filenames don't need to be absolute. – user207421 Feb 21 '22 at 09:37
  • 1. The `src` directory won't be there at runtime. 2. Resources are not files. 3. You can't overwrite resources. – user207421 Feb 21 '22 at 09:38
  • @user207421 The question said it was an absolute path, and it wasn't. That's what. – khelwood Feb 21 '22 at 09:38
  • @khelwood No it doesn't. It says 'entire path', whatever that means. – user207421 Feb 21 '22 at 09:39
  • @user207421 The question *said* "I am passing an entire absolute path, which I dont want to". Not *says*. – khelwood Feb 21 '22 at 09:40
  • The problem might be that you write and read the same file inside the try block. You write without a flush. Try to read the file outside the try block. So then you can be sure that the written file is closed. – vanje Feb 21 '22 at 09:55

0 Answers0