将JSON与JAVA NIO一起使用

时间:2018-05-02 14:43:33

标签: java json nio

我有一个使用json文件的程序。我在一个文件中写了一个jsonobject,然后我从文件中读取并解析它。

用于写入我使用的文件:

File file=new File(nomeFile);


        try {

            file.createNewFile();
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(obj.toJSONString());
            fileWriter.flush();
            fileWriter.close();


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

并阅读:

try {
            FileReader f=new FileReader(file);

            obj =parser.parse(f);
            JSONObject jsonObj = (JSONObject) obj;

//and i do the get

现在我必须更改此代码以使用NIO而不是IO

有可能吗? 我该怎么做? 感谢

2 个答案:

答案 0 :(得分:0)

您可以查看此文章how to read with NIOhow to write with NIO

快速尝试:

写作:

Path path = Paths.get("src/main/resources/question.txt");

String question = "To be or not to be?";

Files.write(path, question.getBytes());

阅读:

Path path = Paths.get("src/main/resources/shakespeare.txt");

try {

  Files.lines(path).forEach(System.out::println);//print each line

} catch (IOException ex) {

  ex.printStackTrace();//handle exception here

}

答案 1 :(得分:-1)

<强> WRITE:

Gson gson = new Gson();
try (FileWriter fw = new FileWriter(CLI_FILES_DIR + File.separator + "applications" + File.separator + "yourFile.json")) {
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(gson.toJson(yourObject));
    bw.flush();
    bw.close();
} catch (IOException e) {
    logger.error("IOException: {}", e.getMessage(), e);
}

<强> READ:

try (BufferedReader bufferedReader = new BufferedReader(new FileReader(CLI_FILES_DIR + File.separator + "applications" + File.separator + "yourFile.json"))) {
    YourObject yourObject = gson.fromJson(bufferedReader, YourObject.class);
    ...
} catch (IOException e) {
    logger.error("IOException: {}", e.getMessage(), e);
}

您可以找到完整的样本here