read Xml Json Properties 汇总

allTypes_readXmlJsonProperties

git地址: https://github.com/wei198621/allTypes_readXmlJsonProperties

读取本地计算机上的文件

************************ 01 Simple 读取本地磁盘文件 *********

本地磁盘放置文件 D://temp//tempdata//product4FileReader.txt

{
  "Data": {
    "code": "S",
    "msg": null,
    "obj": [
      {
        "productmodel": "XRT20",
        "groupname": "",
        "groupcode": ""
      },
      {
        "productmodel": "XRT40",
        "groupname": "",
        "groupcode": ""
      },
      {
        "productmodel": "GR15K",
        "groupname": "混凝土搅拌车",
        "groupcode": "37"
      },
      {
        "productmodel": "HBC37V",
        "groupname": "泵车",
        "groupcode": "03"
      },
      {
        "productmodel": "HZS40",
        "groupname": "混凝土搅拌站",
        "groupcode": "09"
      },
      {
        "productmodel": "LGWEF26514A004390",
        "groupname": "通用产品组",
        "groupcode": "00"
      }
    ]
  },
  "ErrorCode": 0,
  "Message": null
}

三种方式读取本地磁盘上面的文件

--------------------------ReadByFileReaderTest-----------------

  • new BufferedReader( )
  •                new FileReader( )
    
  •                                new File( )
    

-----------------------ReadByFileInpuStream-----------------

  • new BufferedReader( )
  •                new InputStreamReader(  )
    
  •                                       new InputStream()
    

--------------------ReadByFileInputStream02---------------

  • new BufferedInputStream( )
  •                     new FileInpuStream( )
    

读取程序配置文件

************************ 0102 Simple 读取resource下面的properties文件 *********************************

https://www.jianshu.com/p/efdd1a526939
Java 读取配置文件的五种方式

最原始方法读取resources目录下properties文件

--------------------------ReadPropertiesTest---------------

  • props.load ( )
  •         new InputStreamReader(  )
    
  •                                ReadPropertiesTest.class.getClass().getResourceAsStream(path);
    

在这里插入图片描述

PropertiesLoaderUtils(springframework提供)

------------------------ReadPropertiesTest04---------------
org.springframework.core.io.support.PropertiesLoaderUtils;
PropertiesLoaderUtils.loadAllProperties(fileName); 直接加载数据到 Properties spring就是好一步到位
在这里插入图片描述

dom4j

********************** 02 dom4j *********************************
参考文章 :
https://blog.csdn.net/linmengmeng_1314/article/details/79975599
--------------Dom4jTest---------------

Dom4jTest能够成功读取 project 这个节点

0201 引入配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>javaSum</artifactId>
        <groupId>com.tiza.leo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>readPropertiesXmlJson</artifactId>


    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>


</project>

Dom4j02CreateTest

---------注意配置文件位置需要是运行环境resource目录的本地计算机路径-------
String localFilePath = “D:\temp\tempdata\”;
String fileName = “dom4jhtml20200815.html”;
使用dom4j 在本地计算机目录 d:\temp\tempdata\下创建xml文件


    /**
     * @Description: 建立一个XML文档
     * @Param:
     * @return:
     * @date: 2020/5/12
     */
    public static int createXMLFile2(String localFileName) throws IOException {
        int returnValue = 0;

        org.dom4j.Document document = org.dom4j.DocumentHelper.createDocument();

        org.dom4j.Element books = document.addElement("books");
        books.addComment(" thie is a test for dom4j ,weilei 2020");

        org.dom4j.Element bookL1 = books.addElement("book");
        bookL1.addAttribute("show", "yes");

        org.dom4j.Element titleElement = bookL1.addElement("title");
        titleElement.setText("Dom4j tutorials");

        /** 类似的完成后两个book */
        bookL1 = books.addElement("book");
        bookL1.addAttribute("show", "yes");
        titleElement = bookL1.addElement("title");
        titleElement.setText("Lucene Studing");
        bookL1 = books.addElement("book");
        bookL1.addAttribute("show", "no");
        titleElement = bookL1.addElement("title");
        titleElement.setText("Lucene in Action");

        /** 加入owner节点 */
        org.dom4j.Element ownerElement = books.addElement("owner");
        ownerElement.setText("O'Reilly");

        File f = new File(localFileName);
        XMLWriter writer = new XMLWriter(new FileWriter(f));
        writer.write(document);
        writer.close();
        return returnValue;
    }

最终文件内容如下图,所有这些都是代码一点一点品出来的
在这里插入图片描述

Dom4j03ModifyTest

//需要是本地真实路径
String localPath = “D:\temp\tempdata\”;
String fileName = “dom4jhtml20200814.html”;
//修改一个文档
ModifyXmlFile(localPath, fileName, “dom4jhtmlNew.html”);


    public static int ModifyXmlFile(String localPath, String filename, String newFileName) {
        int returnVal = 0;

        File f = new File(localPath + filename);

        try {
            org.dom4j.io.SAXReader saxReader = new SAXReader();
            org.dom4j.Document doc = saxReader.read(f);

            /** 修改内容之一: 如果book节点中show属性的内容为yes,则修改成no */
            /** 先用xpath查找对象 */
            List list = doc.selectNodes("/books/book/@show");
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) {
                org.dom4j.Attribute attr = (Attribute) iterator.next();
                if (attr.getValue().equals("yes")) {
                    attr.setValue("no");
                }
            }

            /* 修改内容之二: 把owner项内容改为Tshinghua
             * 并在owner节点中加入date节点,date节点的内容为2004-09-11,还为date节点添加一个属性type
             */
            list = doc.selectNodes("/books/owner");
            iterator = list.iterator();
            if (iterator.hasNext()) {
                org.dom4j.Element ownerE = (org.dom4j.Element) iterator.next();
                ownerE.setText("Tshinghua");
                org.dom4j.Element dateE = ownerE.addElement("date");
                dateE.setText("20200813");
                dateE.addAttribute("type", "typeLaoLi");
            }



            try {
                File fileNew = new File(localPath + newFileName);
                XMLWriter writer = new XMLWriter(new FileWriter(fileNew));
                writer.write(doc);
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return returnVal;

    }

03 jsoup

jsoup读取resources目录下文件

package com.tz.leo.jsoupTest;

import cn.hutool.core.util.CharsetUtil;

import java.io.File;
import java.io.IOException;

/**
 * Author: tz_wl
 * Date: 2020/5/12 18:32
 * Content:
 */
public class jsoup01BySelect {

    static org.jsoup.nodes.Document doc;
    public static void main(String[] args) throws IOException {

        File f =new File(ClassLoader.getSystemResource("jsoupHtml4Select.html").getPath());
        if(!f.exists()){
            return;
        }
        doc =org.jsoup.Jsoup.parse(f, CharsetUtil.UTF_8);

        //像 jquery 那样的选择器语法
        show("选择所有的超链", "a");
        show("根据id进行选择", "#logocover");
        show("根据class进行选择", ".clearfloat");
        show("根据属性进行选择", "[href]");
        show("有属性以tar开头", "[^tar]");
        show("根据属性值选择", "[type='application/javascript']");
        show("属性值以什么开头", "[href^='http://www.oracle.com']");
        show("属性值以什么结尾", "[href$='index.html']");
        show("属性值包含什么", "[href*='download']");

    }


    private static void show(String text,String selector){
        show(text,selector,3);
    }

    private static void show(String text,String selector,int limit){
        org.jsoup.select.Elements es=doc.select(selector);
        if(es.size()>1){
            System.out.println(String.format("%s - 使用的选择器是: \"%s\" \t (最多显示 %d 条 )", text,selector,limit));
        }else{
            System.out.println(String.format("%s - 使用的选择器是: \"%s\"", text,selector));
        }
        int i=0;
        for(org.jsoup.nodes.Element  e: es){
            if(i++<limit){
                System.out.println(e);
            }
        }
        System.out.println();
    }

}

jsoup02Modify ----> 修改html文件
//需要是本地真实路径
String localPath = “D:\04_CodeFromNet\allTypes_readXmlJsonProperties\_03jsoup\src\main\resources\”;

jsoup03GetData
获取数据源有三种
* 1. 基于字符串方式
* 2. 基于文件方式
* 3. 基于URL方式
String localFileName = “D:\04_CodeFromNet\allTypes_readXmlJsonProperties\_03jsoup\src\main\resources\jsoup03Simple.html”;

jsoup04GetElement

     类似js  jsoup 获取元素 通过 id ,标签,类名,属性 获取元素
package com.tz.leo.jsoupTest;

import cn.hutool.core.util.CharsetUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;

/**
* Author: tz_wl
* Date: 2020/4/24 15:44
* Content: 获取元素 通过 id ,标签,类名,属性 获取元素
*/
public class jsoup04GetElement {
 public static void main(String[] args) throws IOException {

     String localFileName= "D:\\04_CodeFromNet\\allTypes_readXmlJsonProperties\\_03jsoup\\src\\main\\resources\\jsoup04GetElement.html";
     File f=new File(localFileName);
     if(!f.exists()){
         return;
     }

     //通过id 获取元素
     Document doc = Jsoup.parse(f, CharsetUtil.UTF_8);
     Element ele = doc.getElementById("productName");
     System.out.println(ele);
     System.out.println("******************************");

     //通过标签获取元素
     Elements eles= doc.getElementsByTag("a");
     System.out.println("******************************");
     show(eles);
     System.out.println("******************************");

     //通过类名称获取
     eles = doc.getElementsByClass("RightBox");
     show(eles);
     System.out.println("******************************");

     //通过属性获取
     eles=doc.getElementsByAttribute("name");
     show(eles);
     System.out.println("******************************");

 }

 private static void show(Elements es){
     for(Element e: es){
         System.out.println(e);
     }
 }
}

五种获取resources目录下文件方式

jsoup05GetAttr
获取内容和文本
在这里插入图片描述

  //https://blog.csdn.net/Captain249/article/details/98172911
        //多重获取路径方式

        String strClassGetResource= jsoup05GetAttr.class.getResource("/jsoup04GetElement.html").getPath();
        String strClassGetClassLoader =jsoup05GetAttr.class.getClassLoader().getResource("jsoup04GetElement.html").getPath();

        String strClassLoader =ClassLoader.getSystemClassLoader().getResource("jsoup04GetElement.html").getPath();
        String strClassLoader2 =ClassLoader.getSystemResource("jsoup04GetElement.html").getPath();

        String strThread =Thread.currentThread().getContextClassLoader().getResource("jsoup04GetElement.html").getPath();

       

04 jackson

JacksonUtil ww喜欢用的类 暂时没有示例

05 fastjson

https://blog.csdn.net/weixin_40076255/article/details/89373051

------------------------JSONObject------------------------
引用com.alibaba.fastjson jar包

com.alibaba
fastjson
1.2.62

手工设置一个json对象,然后打印 json 字符串

package com.tz.leo.JsonObject03;

import com.alibaba.fastjson.JSON;
import com.tz.leo.JsonObject03.beans.Cmd81Bean;
import com.tz.leo.JsonObject03.beans.TimeBean;
import com.tz.leo.JsonObject03.util.util01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Optional;

/**
 * Author: tz_wl
 * Date: 2020/8/21 17:24
 * Content:
 */
public class mainTest {

    public static void main(String[] args) throws IOException {
        System.out.println("=====================001======================");


        // System.out.println("true = " + true);
        InputStream inputStream = mainTest.class.getResourceAsStream("/originalData81.txt");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String str = bufferedReader.readLine();

        //转换为json字符串
        System.out.println("=====================01======================");
        String strJson = util01.parse2JsonStr(str);
        System.out.println("strJson = " + strJson);

        //str 转换为 Array
        System.out.println("=====================02======================");
        List<Cmd81Bean> cmd81List = JSON.parseArray(strJson, Cmd81Bean.class);
        System.out.println("cmd81List = " + cmd81List);

        //按照  getTimeList.size() 倒叙排序后  取第一个记录
        System.out.println("======================03    =================");
        Optional<Cmd81Bean> first = cmd81List.stream().sorted().findFirst();
        System.out.println("first = " + first);

        //打印原始数据
        System.out.println("======================04=====================");
        List<TimeBean> timeListOriginal = first.get().getTimeList();
        System.out.println("原始数据 = " +  timeListOriginal);
        System.out.println("");
        System.out.println("");
        System.out.println("");
        System.out.println("");
        //打印处理后数据
        System.out.println("======================05=====================");
        List<TimeBean> dateTimeJsons = util01.dateTimeFilter(timeListOriginal);
        System.out.println("处理后数据 = " +  dateTimeJsons);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值