Java - 更新多个文件中特定键的json值

时间:2016-09-29 15:14:23

标签: java json

我是处理json文件的新手。 假设所有文件都包含key1

  • file1.txt - &gt; #include <pthread.h> #include <nacl_io.h> ... pthread_t handle_msg_thread; void *handleMsgThreadFunc(void * data); // Calls function foo() class MyInstance : public pp::Instance { public: explicit MyInstance(PP_Instance instance) :pp::Instance(instance) { nacl_io_init_ppapi(instance, pp::Module::Get()->get_browser_interface()); pthread_create(&handle_msg_thread, NULL, &handleMsgThreadFunc, NULL); } ... }
  • file2.txt - &gt; {"key1":"ab","key2":"cd","key3":"ef"}
  • file3.txt - &gt; {"key1":"gh","key4":"ij","key5":"kl"}

现在我想为所有文件制作“key1”:“xyz”,其他键保持该文件中存在的相同值。 我曾尝试过以下代码。

{"key1":"mn","key3":"op","key4":"qr", "key5":"st"}
  • file1的预期输出:String filePath = "D:\\json" File folder = new File(filePath); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { JSONObject js = new JSONObject(); js.remove("key1"); js.put("key1", xyz); try (FileWriter fw = new FileWriter(filePath+ "\\" + listOfFiles[i].getName())) { fw.write(js.toString()); } catch (Exception e) { e.printStackTrace(); } }
  • 但我只有{"key1":"xyz","key2":"cd","key3":"ef"}其他人都没了。

0 个答案:

没有答案