首页 > 编程语言 >Java--进阶

Java--进阶

时间:2023-06-10 14:45:21浏览次数:36  
标签:Java 进阶 -- System String new println import out

高级文本处理

Locale类

image-20230602001908576
		// 返回Java所支持的全部国家和语言的数组
		Locale[] localeList = Locale.getAvailableLocales();

		for (Locale locale : localeList)
		{
			System.out.println(locale.getLanguage() + "_" + locale.getCountry());
			System.out.println(locale.getDisplayLanguage() + "_" + locale.getDisplayCountry());
		}

		System.out.println("=========================");
		Locale myLocale = Locale.getDefault();
		System.out.println(myLocale); //zh_CN
		System.out.println(Locale.CHINA); //zh_CN

		myLocale = new Locale("en", "US"); //语言 国家, 强制换成en_US
		System.out.println(myLocale); //en_US

语言文件

image-20230602002014907

resourceBundle类

image-20230602002116863 image-20230602002648054

附:配置文件读取路劲

image-20230603220622412

注意:resources文件中含有如下文件:image-20230602002828253

其中msg_zh_CN.properties中含有如下:name=\u9648\u826f\u80b2

其中\u9648\u826f\u80b2为陈良育的Unicode编码见上面关于语言文件的介绍

使用native对ASCII转码

  1. 打开note记事本编写中文,并将后缀改为.properties ,另存为编码格式ASCII编码。存放至resource目录下
  2. java-基础部分,properties为hashtable,读取对应键值对
	public static void main(String[] args) {
		Locale myLocale = Locale.getDefault();	//获取系统默认的语言

		System.out.println(myLocale); //zh_CN

		// 根据指定语言_国家环境加载资源文件
		ResourceBundle bundle = ResourceBundle.getBundle("msg", myLocale);

		// 从资源文件中取得的消息
		System.out.println(bundle.getString("name"));  //陈良育
	}

高级字符串

正则表达式

    private static String REGEX = "a*b"; //*表示限定前面的a可以有0或者多个。
    private static String INPUT = "aabfooaabfooabfoobcdd";
    private static String REPLACE = "-";
 
    public static void main(String[] args) {
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(INPUT); // get a matcher object
        StringBuffer sb = new StringBuffer();
        String output;
        //全部替换
         //方法1.
        while(m.find()){
            m.appendReplacement(sb,REPLACE);
        }
        //将最后的尾巴字符串附加上
        m.appendTail(sb); 
        System.out.println(sb.toString());
         //方法2.
        output = m.replaceAll(REPLACE);
        System.out.println(output);
    }

String2List

		List<String> names = new LinkedList<String>();
        names.add("Xiaohong");
        names.add("Xiaoming");
        names.add("Daming");
        names.add("Xiaohei");
        
        //从ArrayList变到字符串
        String str1 = String.join(",", names);  //String.join, JDK 8 引入
        System.out.println(str1);
       
        String str2 = StringUtils.join(names, ",");  //Apache Commons Lang
        System.out.println(str2);
        
        //从字符串变回ArrayList
        List<String> names2 = Arrays.asList(str2.split(",")); 
        for(String name:names2)
        {
        	System.out.println(name);
        }
        
        //StringUtils 可以支持更多数据类型
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(3);
        ids.add(5);
        String str3 = StringUtils.join(ids, ",");  
        System.out.println(str3);

GuavaUtil

import java.util.ArrayList;
import java.util.List;

import com.google.common.base.CaseFormat;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

public class GuavaUtil {
	public static void main(String[] args) throws Exception {
        List<Integer> list = new ArrayList<Integer>();
        list.add(123);
        list.add(456);
        System.out.println(list);
        
        //直接初始化List数组
        List<Integer> integers = Lists.newArrayList(123, 456);
        System.out.println(integers);

        //拆分字符串,忽略空字符串
        Iterable<String> split = Splitter.on(',')
                .trimResults()
                .omitEmptyStrings()
                .split("123,321,,   abc");

        for (String s : split) {
            System.out.println(s);
        }
        
         //驼峰命名
        String s1 = "CONSTANT_NAME";
        String s2 = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, s1);
        System.out.println(s2); //constantName;

        
        String a = "123,321,,   abc";
        String[] as = a.split(",");
        
        for(int i=0;i<as.length;i++)
        {
        	if(null == as[i] || as[i].length()<=0)
        	{
        		continue;
        	}
        	else
        	{
        		System.out.println(as[i].trim());
        	}
        }       
    }
}

String2InputStream

public class String2InputStream {

    public static void main(String[] args) {
    	//构造字符串列表
    	List<String> names = new LinkedList<String>();
        names.add("Xiaohong");
        names.add("Xiaoming");
        names.add("Daming");
        names.add("Xiaohei");
        
        //合并为一个字符串,以逗号相连
        String nameStr = String.join(",",names);

        System.out.println(nameStr);
        
        //将字符串作为默认的输入流
        InputStream in = IOUtils.toInputStream(nameStr, Charsets.toCharset("UTF-8"));
        //重置系统的输入流
        System.setIn(in);
        
        //模拟键盘输入  这也是OJ平台测试用例输入的原理
        //此处也可以换成一个文件输入流
        Scanner sc=new Scanner(System.in);
        sc.useDelimiter(",");
        while(sc.hasNext())
        {
            System.out.println(sc.next());
        }
    }
}

上述代码部分使用文件输入流实现(当然这部分与String2InputStream没什么关系)

public class String2InputStream {

    // 文件 abc.txt 中内容为:Xiaohong,Xiaoming,Daming,Xiaohei
    public static void main(String[] args) {
        
        //模拟键盘输入  这也是OJ平台测试用例输入的原理
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try{
            fis = new FileInputStream("D:/VS-Code-C/mooc/demo/src/main/resources/abc.txt");
            isr = new InputStreamReader(fis,"UTF-8");
            br = new BufferedReader(isr);
            // String line = null;
            // while((line = br.readLine())!=null){
            //     System.out.print(line);
            // }
            Scanner sc= new Scanner(fis);
            sc.useDelimiter(",");
            while(sc.hasNext()){
                System.out.println(sc.next());
            }
        }catch(Exception e){
            e.getStackTrace();
        }finally{
            try{
                br.close();
            }catch(Exception e){
                e.getStackTrace();
            }
        }
    }
}

高级文件处理

XML

image-20230606213610954
XML结构
image-20230606213906275

image-20230606213821264

XML扩展
image-20230606214044384 image-20230606214103477
image-20230606214940425
image-20230606214123863

image-20230606214917681

XML解析
image-20230607001417156
DOM
image-20230607001522371 image-20230607001634275

image-20230607001616493

DOM 读

image-20230610140912836

users.xml

<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user id="0">
        <name>Mary</name>
        <age>23</age>
        <sex>Female</sex>
    </user>
    <user id="1">
        <name>Mike</name>
        <age>24</age>
        <sex>Male</sex>
    </user>
    <user id="2">
        <name>Alice</name>
        <age>23</age>
        <sex>Female</sex>
    </user>
    <user id="3">
        <name>Tom</name>
        <age>24</age>
        <sex>Male</sex>
    </user>
</users>
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

//下面采用两种方法
public static void recursiveTraverse()
    {
    	try 
    	{
    		//采用Dom解析xml文件
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse("demo\\src\\main\\resources\\users.xml");
            
            //获取所有的一级子节点
            NodeList usersList = document.getChildNodes();
            System.out.println(usersList.getLength());  //1  
            
            for (int i = 0; i < usersList.getLength(); i++) 
            {
                Node users = usersList.item(i);         //1  users 
                
                NodeList userList = users.getChildNodes(); //获取二级子节点user的列表
                System.out.println("==" + userList.getLength()); //9
                
                for (int j = 0; j < userList.getLength(); j++) //9
                {
                    Node user = userList.item(j);
                    if (user.getNodeType() == Node.ELEMENT_NODE)
                    {
                    	 NodeList metaList = user.getChildNodes();
                         System.out.println("====" + metaList.getLength()); //7
                         
                         for (int k = 0; k < metaList.getLength(); k++) //7
                         {
                         	//到最后一级文本
                        	Node meta = metaList.item(k);
                        	if (meta.getNodeType() == Node.ELEMENT_NODE)
                        	{
                        		System.out.println(metaList.item(k).getNodeName() 
                        				+ ":" + metaList.item(k).getTextContent());
                        	}                                                              
                         }                    
                         System.out.println();
                    }                   
                }
            }            
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }   
    
    public static void traverseBySearch()
    {
    	try 
    	{
    		//采用Dom解析xml文件
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse("demo\\src\\main\\resources\\users.xml");
            
            Element rootElement = document.getDocumentElement();         

            NodeList nodeList = rootElement.getElementsByTagName("name"); 
            if(nodeList != null) 
            { 
               for (int i = 0 ; i < nodeList.getLength(); i++) 
               { 
                  Element element = (Element)nodeList.item(i);                  
                  System.out.println(element.getNodeName() + " = " + element.getTextContent());
               } 
            }             
        } catch (Exception e) {
            e.printStackTrace();
        } 	
    }  

DOM 写

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public static void main(String[] args) {
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
			
			//新创建一个Document节点
			Document document = dbBuilder.newDocument();
			if (document != null) 
			{
				Element docx = document.createElement("document");	//都是采用Document创建元素		
				Element element = document.createElement("element");
				element.setAttribute("type", "paragraph"); 
				element.setAttribute("alignment", "left"); //element增加2个属性
				
				Element object = document.createElement("object");
				object.setAttribute("type", "text");
				
				Element text = document.createElement("text");
				text.appendChild(document.createTextNode("abcdefg")); //给text节点赋值
				Element bold = document.createElement("bold");
				bold.appendChild(document.createTextNode("true"));    //给bold节点赋值
				
				object.appendChild(text);      //把text节点挂在object下
				object.appendChild(bold);      //把bold节点挂在object下
				element.appendChild(object);   //把object节点挂在element下
				docx.appendChild(element);	   //把element节点挂在docx下		
				document.appendChild(docx);    //把docx挂在document下
				
				TransformerFactory transformerFactory = TransformerFactory.newInstance();
				Transformer transformer = transformerFactory.newTransformer();
				DOMSource source = new DOMSource(document);
				
				//定义目标文件
				File file = new File("demo\\src\\main\\resources\\dom_result.xml");
				StreamResult result = new StreamResult(file);
		 	 
				//将xml内容写入到文件中
				transformer.transform(source, result);
				
				System.out.println("write xml file successfully");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}	
image-20230610141403107

dom_result.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document>
    <element alignment="left" type="paragraph">
        <object type="text">
            <text>abcdefg</text>
            <bold>true</bold>
        </object>
    </element>
</document>
SAX

image-20230607001709273

Stax
image-20230607001726901

JSON

image-20230607003508260

JSONObject和JSONArray

image-20230607003523911

JAVA中的JSON处理

image-20230607003657224

image-20230607003751666

采用Jackson来处理JSON

books2.json

[
    {
      "category": "COOKING",
      "title": "Everyday Italian",
      "author": "Giada De Laurentiis",
      "year": "2005",
      "price": 30
    },
    {
      "category": "CHILDREN",
      "title": "Harry Potter",
      "author": "J K. Rowling",
      "year": "2005",
      "price": 29
    },
    {
      "category": "WEB",
      "title": "Learning XML",
      "author": "Erik T. Ray",
      "year": "2003",
      "price": 39
    }
  ]

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * 采用Jackson来处理JSON
 * @author Tom
 *
 */

public class JacksonTest {

	public static void main(String[] args) throws Exception {
		testJsonObject();
		System.out.println("=========华丽丽的分割线==============");
		testJsonFile();
	}
	
	static void testJsonObject() throws IOException {
		ObjectMapper om = new ObjectMapper();
		
		//构造对象
    	Person p = new Person();
    	p.setName("Tom");
    	p.setAge(20);
    	p.setScores(Arrays.asList(60,70,80));
    	
    	//将对象解析为json字符串
		String jsonStr = om.writeValueAsString(p);
		System.out.println(jsonStr);
		
		//从json字符串重构对象
		Person p2 = om.readValue(jsonStr, Person.class);
		System.out.println(p2.getName());
		System.out.println(p2.getAge());
		System.out.println(p2.getScores());
		
		//从json字符串重构为JsonNode对象
		JsonNode node = om.readTree(jsonStr);
		System.out.println(node.get("name").asText());
		System.out.println(node.get("age").asText());
		System.out.println(node.get("scores"));		
	}
	
	static void testJsonFile() throws IOException {
		ObjectMapper om = new ObjectMapper();
		
		//从json文件中加载,并重构为java对象
		File json2 = new File("demo\\src\\main\\resources\\books2.json");
		List<Book> books = om.readValue(json2, new TypeReference<List<Book>>(){});
		for (Book book : books) {
			System.out.println(book.getAuthor());
			System.out.println(book.getTitle());
		}
	}	
}
采用Google GSON来处理JSON
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
public class GsonTest {
	public static void main(String[] args) {
		testJsonObject();
		System.out.println("=========华丽丽的分割线==============");
		testJsonFile();
	}
	public static void testJsonObject() {
		//构造对象
    	Person p = new Person();
    	p.setName("Tom");
    	p.setAge(20);
    	p.setScores(Arrays.asList(60,70,80));
		
    	//从Java对象到JSON字符串
		Gson gson = new Gson();
		String s = gson.toJson(p);
		System.out.println(s); //{"name":"Tom","age":20,"scores":[60,70,80]}
		
		//从JSON字符串到Java对象
		Person p2 = gson.fromJson(s, Person.class);
		System.out.println(p2.getName());  //Tom
		System.out.println(p2.getAge());   //20
		System.out.println(p2.getScores());//[60, 70, 80]
		
		//调用GSON的JsonObject
		JsonObject json = gson.toJsonTree(p).getAsJsonObject(); //将整个json解析为一颗树
		System.out.println(json.get("name"));  //"Tom"
		System.out.println(json.get("age"));   //20
		System.out.println(json.get("scores"));//[60,70,80]
		
	}
	
	public static void testJsonFile() {
		Gson gson = new Gson();
		File file = new File("demo\\src\\main\\resources\\books2.json");
		
        try (FileReader reader = new FileReader(file)) {
        	List<Book> books = gson.fromJson(reader, new TypeToken<List<Book>>(){}.getType());
            
        	for(Book book : books)
        	{
        		System.out.println(book.getAuthor() + ",  " + book.getTitle());
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}
采用org.json包来解析JSON

books.json

{
  "books": [
    {
      "category": "COOKING",
      "title": "Everyday Italian",
      "author": "Giada De Laurentiis",
      "year": "2005",
      "price": 30.00
    },
    {
      "category": "CHILDREN",
      "title": "Harry Potter",
      "author": "J K. Rowling",
      "year": "2005",
      "price": 29.99
    },
    {
      "category": "WEB",
      "title": "Learning XML",
      "author": "Erik T. Ray",
      "year": "2003",
      "price": 39.95
    }
  ]
}
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class OrgJsonTest {
	public static void main(String[] args) {
		testJsonObject();
		System.out.println("=========华丽丽的分割线==============");
		testJsonFile();
	}
    public static void testJsonObject() {
    	//构造对象
    	Person p = new Person();
    	p.setName("Tom");
    	p.setAge(20);
    	p.setScores(Arrays.asList(60,70,80));
    	
    	
    	//构造JSONObject对象
    	JSONObject obj = new JSONObject(); 	
    	
        //string
    	obj.put("name", p.getName());
        //int
    	obj.put("age", p.getAge());
        //array
        obj.put("scores", p.getScores());
        //null
        //object.put("null", null);
        System.out.println(obj);        
        
        System.out.println("name: " + obj.getString("name"));
        System.out.println("age: " + obj.getInt("age"));
        System.out.println("scores: " + obj.getJSONArray("scores"));
    }

    public static void testJsonFile() {
    	File file = new File("books.json");
        try (FileReader reader = new FileReader(file)) {
        	//读取文件内容到JsonObject对象中
            int fileLen = (int) file.length();
            char[] chars = new char[fileLen];
            reader.read(chars);
            String s = String.valueOf(chars);
            JSONObject jsonObject = new JSONObject(s);
            
            //开始解析JSONObject对象
            JSONArray books = jsonObject.getJSONArray("demo\\src\\main\\resources\\books");
            List<Book> bookList = new ArrayList<>();
            for (Object book : books) {
            	//获取单个JSONObject对象
                JSONObject bookObject = (JSONObject) book;
                Book book1 = new Book();
                book1.setAuthor(bookObject.getString("author"));
                book1.setYear(bookObject.getString("year"));
                book1.setTitle(bookObject.getString("title"));
                book1.setPrice(bookObject.getInt("price"));
                book1.setCategory(bookObject.getString("category"));
                bookList.add(book1);
            }
            
            for(Book book:bookList)
            {
            	System.out.println(book.getAuthor() + ",  " + book.getTitle());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
JSON与XML的比较

image-20230607003827446

标签:Java,进阶,--,System,String,new,println,import,out
From: https://www.cnblogs.com/komorebi-514/p/17471255.html

相关文章

  • uniapp-黑马优选学习01
    01.IDE使用HBuilderX02.scss/sass插件安装:为了方便样式的编写   地址: https://ext.dcloud.net.cn/plugin?name=compile-node-sass03.快捷键方案的设置、IDE主题色的设置、基本设置(ctlr加alt加逗号 :  ctrl+alt+, )    >>其它基本......
  • Jdk 中自带的工具
    JDK(JavaDevelopmentKit)自带了很多工具,以下是一些常用的工具及其作用:jstat:用于监视JVM中各种运行时状态信息,如类加载、内存、垃圾回收等。jmap:用于导出JVM内存映像,可以用于内存泄漏分析、GC分析等。jstack:可以用于查看Java线程的堆栈信息,帮助定位线程死锁、线程......
  • 机器学习——泰坦尼克号幸存者预测及分析
    1.项目背景泰坦尼克号: 是当时世界上体积最庞大、内部设施最豪华的客运轮船, 于1909年3月31日动工建造, 1912年4月2日完工试航.于1912年4月10日,在南安普敦港的海洋码头,启程驶往纽约,开始了它的第一次,也是最后一次的航行. 泰坦尼克号将乘客分为三个等级:三等舱位于......
  • Spring中的三级缓存
    Spring中的三级缓存是针对bean的加载和创建过程而设计的。在Spring容器中,每次请求获取一个bean时,Spring首先检查一级缓存、二级缓存和三级缓存中是否已经存在该bean,如果存在,则直接返回缓存中的实例对象,否则才进行bean的创建。三级缓存包括:singletonObjects缓存:一级......
  • VSCode使用指定的 SOCKS 代理进行网络连接
    VSCode使用指定的SOCKS代理进行网络连接June10,2023vscode怎么打开settings.json文件?ChatGPT在VisualStudioCode(VSCode)中,打开settings.json文件的步骤如下:打开VisualStudioCode。点击左上角的“文件”菜单,然后选择“首选项”>“设置”(或者你可......
  • 地址空间以及编译模式
    Linux下32位环境的用户空间内存分布: Linux下64位环境的用户空间内存分布:前面讲到,在64位环境下,虚拟地址虽然占用64位,但只有最低48位有效。故从0000800000000000~FFFF800000000000,棕色FFFF所代表的这十六位就变成了无效区域(未定义)。 程序代码区用来保存函数体的二进制代码......
  • 能让你生活更容易的6个AI组件(除了ChatGPT)
    目录1、Tom:AI驱动的演示构建者2、QuillBot:一个AI工具可以增强你的写作能力3、Descript:更容易的视频与音频的编辑4、BHuman:上规模的AI驱动的个性化视频5、CleanupPictures6、NotionAI:写作更快并且增加你的创造力但是,那不是全部。除了生成文本,NotionAI也是一个强大的编辑器。他......
  • 在Linux系统中创建虚拟网卡
    .....创建虚拟网卡:>$sudoiplinkadddevvirnet0typeveth其中virnet0是虚拟网卡的名字,可以换成你喜欢的名字。接下来为虚拟网卡配置IP地址:>$sudoipaddradd192.168.99.2/24devvirnet0激活虚拟网卡,以下两条命令使用任意一条均可:>$sudoiplinksetv......
  • js笔记_函数
    函数定义方式一绝对值函数functionabs(x){returnx;}else{return-x;}一旦执行到return代表函数结束,返回结果。如果没有执行return,函数执行完也会返回结果,结果就是undefined定义方式二varabs=function(x){if(x>=0)returnx;}else{return-x;}}function(x){.......
  • 获取网站元数据(标题、描述内容、图标)
    做个网站导航链接的小项目,每次输入网址、标题等一系列信息很麻烦。所以想通过只输入网址自动获取相关内容。问题描述通过输入一个网址,点击按钮后获取该网站的标题、描述内容和图标等信息。最开始打算用vue前端实现功能,但是由于浏览器的同源策略限制,前端无法直接从其他网站获......