java jackson 读写修改json文件

json数据格式:
// {"test":[{"volume":234,"driver":[{"ip":"192.168.1.1"},{"ip":"192.168.1.2"},{"ip":"192.168.1.3"}]},{"volume":234123,"driver":[{"ip":"192.168.1.1"},{"ip":"192.168.1.2"},{"ip":"192.168.1.3"}]}]}
//读
synchronized
public static boolean existInMultiPathConfigFile(long volumeId) { try { ObjectMapper objMap = new ObjectMapper(); System.out.println("array size is 111111111111111111"); JsonNode root = objMap.readTree(new File("/home/test/multipaths.conf")); System.out.println("array size is 2222222222222222222222"); JsonNode node = root.path("test"); System.out.println("array size is " + node.size()); for (int i = 0; i < node.size(); i++) { Long volume = node.path(i).path("volume").asLong(); if (volume.equals(volumeId)) { System.out.println("exist connection in multipaths.conf."); return true; } } } catch (Exception ex) { System.out.println("error to read config file."); return false; } System.out.println("nonexist@@@@@@@@@@@@@@@@@@@@."); return false; } //写 synchronized public static boolean writeMultiPathConfigFile(long volumeId, List<String> ips) { try { ObjectMapper objMap = new ObjectMapper(); JsonNode root = objMap.readTree(new File("/home/test/multipaths.conf")); ArrayNode node = (ArrayNode)root.path("test"); ObjectNode newNode = objMap.createObjectNode(); newNode.put("volume", volumeId); ArrayNode ipArray = objMap.createArrayNode(); for (String ip : ips) { ObjectNode ipNode = objMap.createObjectNode(); ipNode.put("ip", ip); ipArray.add(ipNode); } newNode.put("driver", ipArray); node.add(newNode); OutputStream outputStream = new FileOutputStream(new File("/home/test/multipaths.conf")); objMap.writeValue(outputStream, root); } catch (Exception ex) { System.out.println("error to read config file."); return true; } return false; }
//删除
synchronized public static boolean eraseMultiPathConfigFile(long volumeId) { try { ObjectMapper objMap = new ObjectMapper(); JsonNode root = objMap.readTree(new File("/home/test/multipaths.conf")); JsonNode node = root.path("test"); Iterator<JsonNode> iter = node.iterator(); while (iter.hasNext()) { JsonNode next = iter.next(); System.out.println("erase the match line." + next.get("volume")); if (next.get("volume").asLong() == volumeId) { System.out.println("erase the match line.******************"); iter.remove(); } } OutputStream outputStream = new FileOutputStream(new File("/home/test/multipaths.conf")); objMap.writeValue(outputStream, root); } catch (Exception ex) { System.out.println("error to read config file."); return true; } return false; }

 

转载于:https://www.cnblogs.com/longchang/p/11303981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值