I'm new to handling json files. Assume all the file contains key1
- file1.txt ->
{"key1":"ab","key2":"cd","key3":"ef"}
- file2.txt ->
{"key1":"gh","key4":"ij","key5":"kl"}
- file3.txt ->
{"key1":"mn","key3":"op","key4":"qr", "key5":"st"}
- and so on
Now I want to make "key1":"xyz" for all files and the other keys remains same value present in that file. I had tried the following code.
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();
}
}
- output expected for file1 :
{"key1":"xyz","key2":"cd","key3":"ef"}
- but I got only
{"key1":"xyz"}
rest of them are gone.