# groovydemo **Repository Path**: android100/groovydemo ## Basic Information - **Project Name**: groovydemo - **Description**: groovy使用http,file等 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-03-20 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 一、groovy 与 properties ```groovy // // 参考: // https://www.w3cschool.cn/groovy/groovy_file_io.html // https://www.cnblogs.com/xudong-bupt/p/3758136.html // // class TestProp { public static void main(String[] args) { def filename = "src\\file\\one.properties" def props = new Properties(); props.load(new FileInputStream(filename)); println("===================遍历一=========================") Enumeration enumeration = props.keys(); while (enumeration.hasMoreElements()) { def key = enumeration.nextElement(); def val = props.get(key); println "property : " + key + " = " + val; } println("===================遍历二=========================") Iterator it = props.stringPropertyNames().iterator(); while (it.hasNext()) { String key = it.next(); println(key + ":" + props.getProperty(key)); } println("===================获取方式一=========================") def name = props["name"] def id = props["id"] def age = props["age"] println("name = $name , id = $id , age = $age") println("===================获取方式二=========================") def name2 = props.get("name") def id2 = props.get("id") def age2 = props.get("age") println("name2 = $name2 , id2 = $id2 , age2 = $age2") println("===================获取方式三=========================") def name3 = props.getProperty("name") def id3 = props.getProperty("id") def age3 = props.getProperty("age") println("name3 = $name3 , id3 = $id3 , age3 = $age3") } } ``` # 二、groovy 与 File ```groovy import groovy.json.JsonSlurper import java.text.SimpleDateFormat // https://www.w3cschool.cn/groovy/groovy_file_io.html // Groovy读取文件信息 // https://www.cnblogs.com/alansheng/p/4788237.html class TestFile { public static void main(String[] args) { println("***************** 读取文件 *********************") readFile() println("***************** 写入文件 *********************") writeFile("src\\file\\two.txt") writeFile2("src\\file\\two2.txt") println("***************** 复制文件 *********************") copyFile() println("***************** 操作目录 *********************") handleDictionary() } private static void handleDictionary() { def dir = new File("src", "\\file") if (dir.isDirectory()) { dir.eachFileRecurse { file -> println file } } //使正则表达式匹配文件名 dir.eachFileMatch(~/.*\.txt/) { File it -> println it.name } } private static void copyFile() { //可以写入不同的文件类型,拷贝的只是文件内容 def src = new File("src", "file\\one.txt") def dst = new File("src", "file\\three.txt") if (!dst.exists()) { dst.createNewFile() } dst << src.text } private static void readFile() { new File("src", 'file\\one.txt').eachLine { line -> println line } new File("src", 'file\\one.txt').eachLine { line, lineNum -> println(lineNum + " " + line) } //读取文件的内容到字符串 File file = new File("src", "file\\one.txt") println file.text } def static writeFile(fileName) { new File(fileName).withWriter('utf-8') { writer -> writer.write('The first content of file') writer.write('\n') writer.write('The first content of file') writer.write('\n') writer.write("name : xq") writer.write('\n') writer.write("time : ${getTime()}") } } def static writeFile2(fileName) { def file = new File(fileName) if (file.exists()) file.delete() def printWriter = file.newPrintWriter() // printWriter.write('The first2 content of file') printWriter.write('\n') printWriter.write('The first2 content of file') printWriter.write('\n') printWriter.write("name : xq2") printWriter.write('\n') printWriter.write("time2 : ${getTime()}") printWriter.flush() printWriter.close() } def static getTime() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); return sdf.format(calendar.getTime()); } } ``` # 三、groovy 与 json one.json: ```json [ { "id": "1", "courseID": "数学", "title": "一加一等于几" }, { "id": "2", "courseID": "语文", "title": "请背诵全文" } ] ``` two.json: ```json { "cateid": 53, "name": "狗狗玩具", "children": [ { "type": "cateid", "id": "210", "name": "棉制玩具", "photo": "http://i.epetbar.com/nowater/cates/2014-03/24/fcab37ead00d77bcdddf7dabe6c817d7.jpg" }, { "type": "cateid", "id": "211", "name": "橡胶玩具", "photo": "http://i.epetbar.com/nowater/2016-07/21/14/874299e54a8cf1488d6b1bead8f8e9bb.jpg" }, { "type": "cateid", "id": "212", "name": "塑料玩具", "photo": "http://i.epetbar.com/nowater/cates/2014-03/24/df1ed7120376370a4b5badaae61a0a7e.jpg" }, { "type": "cateid", "id": "213", "name": "手工玩具", "photo": "http://i.epetbar.com/nowater/cates/2014-03/24/6709410560b999ab37ffb9747bb2ee71.jpg" }, { "type": "cateid", "id": "3088", "name": "食用玩具", "photo": "http://i.epetbar.com/nowater/cates/2014-03/24/a5c7619872749790f6d6fd1ff3eccedc.jpg" }, { "type": "cateid", "id": "4157", "name": "木质玩具", "photo": "http://i.epetbar.com/nowater/cates/2014-03/24/e9145de044fd5cec4c9b8ed47360d98f.jpg" }, { "type": "cateid", "id": "4188", "name": "梵米派", "photo": "http://i.epetbar.com/nowater/cates/2015-07/28/45c339f6acb56364132b92f04b090c5c.jpg" } ] } ``` ```groovy import groovy.json.JsonOutput import groovy.json.JsonSlurper import org.apache.groovy.json.internal.LazyMap // https://www.w3cschool.cn/groovy/groovy_file_io.html class TestJson { public static void main(String[] args) { //*************************************************************************** //*** //*** JsonSlurper //*** {} : LazyMap, 空映射 [:] //*** [] : ArrayList, 空集合 [] //*** //*************************************************************************** def jsonSlurper = new JsonSlurper() test1(jsonSlurper) println() println() test2(jsonSlurper) println() println() test3(jsonSlurper) println() println() test4(jsonSlurper) } private static void test1(JsonSlurper jsonSlurper) { def object = jsonSlurper.parseText('{ "name": "John", "ID" : "1"}') println(object.getClass()); if (object instanceof LazyMap && object.size() > 0) { println(object.name); println(object.ID); } } /** * 对象转化为JSON * 在 Groovy 中提供 JsonOutput 将对象解析为 json 字符串。 */ private static void test2(JsonSlurper jsonSlurper) { Person person = new Person("xq", 26) //将对象生成json def json = JsonOutput.toJson(person) //JsonOutput.prettyPrint 输出带有 json 格式 println "0===========================" + json println "1===========================" + JsonOutput.prettyPrint(json) //解析json为map或list def jsonObj = jsonSlurper.parseText(json) println "2===========================" + jsonObj.getClass() if (jsonObj instanceof Map) { println "3===========================" + jsonObj["name"] } } private static void test3(JsonSlurper jsonSlurper) { def jsonObj = jsonSlurper.parseText(new File("src", "file\\one.json").text) println("=====================================" + jsonObj) println("=====================================" + jsonObj.getClass()) //class java.util.ArrayList if (jsonObj instanceof ArrayList && jsonObj.size() > 0) { println("=====================================" + jsonObj.size()) jsonObj.each { println("=============================" + it) println("=============================" + it.getClass()) //class org.apache.groovy.json.internal.LazyMap if (it instanceof LazyMap && it.size() > 0) { println("=============================" + it.size()) it.each { key, value -> println key + "========================" + value } } } } } private static void test4(JsonSlurper jsonSlurper) { def jsonObj = jsonSlurper.parseText(new File("src", "file\\two.json").getText()) println("00==============================" + jsonObj.getClass()) //class org.apache.groovy.json.internal.LazyMap def children = jsonObj["children"] println "20==============================" + children println "21==============================" + children.getClass() println() //class java.util.ArrayList def result = children.findAll { item -> println "30==============================" + item println "31==============================" + item.getClass() //class org.apache.groovy.json.internal.LazyMap item["id"] == "3088" //true or false } println "40==============================" + result } } class Person implements Serializable { private String name private int age Person(String name, int age) { this.name = name this.age = age } String getName() { return name } void setName(String name) { this.name = name } int getAge() { return age } void setAge(int age) { this.age = age } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } ```