Convert a file path to String

Asked

Viewed 199 times

2

I’m in need of help, I need to read a JSON file (I’m using the GSON library), and for that I need to transform a Path variable to a String. Below is the code for better understanding.

public void gravaJson(String nomeArq) {
    Gson gson = new Gson();

    String json = gson.toJson(lista);

    try {
        final Writer writer = new FileWriter(nomeArq);
        gson.toJson(json, writer);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void readJson(String nomeArq) throws FileNotFoundException {
    Path caminho = Paths.get(nomeArq);
    String path; //Preciso converter o caminho para String
    BufferedReader bufferedReader = new BufferedReader(new FileReader(path));

    Gson gson = new Gson();
    Object json = gson.fromJson(bufferedReader, Object.class);

    System.out.println(json.toString());
}

1 answer

2


Try it this way

path = Paths.get(nomeArq).toAbsolutePath().toString();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.