高级文本处理
Locale类
// 返回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
语言文件
resourceBundle类
附:配置文件读取路劲
注意:resources
文件中含有如下文件:
其中msg_zh_CN.properties
中含有如下:name=\u9648\u826f\u80b2
其中\u9648\u826f\u80b2
为陈良育的Unicode编码见上面关于语言文件的介绍
使用native对ASCII转码:
- 打开note记事本编写中文,并将后缀改为
.properties
,另存为编码格式ASCII编码。存放至resource目录下 - 见
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
XML结构
XML扩展
XML解析
DOM
DOM 读
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();
}
}
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
Stax
JSON
JSONObject和JSONArray
JAVA中的JSON处理
采用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();
}
}
}