Groovy’s manipulation of files

Traversal of the file assumes that the original contents of the file are:

Andorid and ios are Good SystemCopy the code

First method: Use eachLine()

EachLine {// print eachLine of content line -> println line} Andorid and ios are Good SystemCopy the code

Second method: Use File getText()

Def content = file.gettext () println content // output hello,worldCopy the code

Is it easier to call a method directly? It is much simpler than Java operation files

Third method: use the file.readlines () method

Def list = file.readlines () list.collect {println it} println "" + list.size() +" And ios are Good System file has 3 linesCopy the code

Conveniently, the readLines() function reads the contents of the file directly into a List, in behavior units, which makes it even easier

The fourth method: read part of the file content

Def reader = file.withReader {reader -> char[] buffer = new char[20] return buffer} def reader = file.withReader {reader -> char[] buffer = new char[20] return buffer} Println reader // prints hello world here is Beijing anCopy the code

How do I copy a file?

Copy the file to another file as follows:

Def copy(String sourcePath, String destPath) {try {def File = new File(destPath) if (! Destfile.exists ()) {destfile.createnewFile ()} //2 Start copy new File(sourcePath). WithReader {reader -> def lines = Destfile.readlines () destfile.withwriter {writer -> lines.each {// write each line to the destination file line -> writer.append(line+"\r\n")}}}  return true } catch (Exception e) { return false } }Copy the code

Read and write object Sometimes we need to write our bean object to a file and then read it when needed.

Def saveObject(Object Object, String path) {try {destFile = new File(path) if (! destFile.exists()) { destFile.createNewFile() } destFile.withObjectOutputStream { out -> out.writeObject(object) } return true } catch (Exception e) { } return false; Def obj = null try {def file = new file (path) if (! File. The exists () {return null} / / 2 read from the file object file. WithObjectInputStream {reader - > obj = reader. The readObject (); } return obj } catch (Exception e) { } return null }Copy the code

Groovy’s manipulation of XML files

/** test.xml file contains the following contents:  <langs type="current"> <language1>Java</language1> <language2>Groovy</language2> <language3>JavaScript</language3> </langs> */ / def langs = new XmlParser().parse("test.xml") // Prints the node attribute println langs.attribute('type') Langs.each {println it.text()} // Outputs current Java Groovy JavaScriptCopy the code

That’s what Groovy does with files