BufferedReader bf = new BufferedReader(new FileReader("/path/to/file"))There is just too many classes to study in Java to do different kinds of file manipulation. Groovy provides a much simpler way to work with files. You just need to create the file object and you are good to go!
File file = new File("C:/temp/test.txt")Most of what we need to do are supported in this class. No need to combine with other classes. Below are some examples on how to do file manipulation in Groovy.
Getting the file size of a Groovy file is easy. You just need to invoke the length() method of a Groovy File object. Here is an example code:
class FileExample { static void main(String[] args) { File file = new File("C:/temp/test.txt") println "The file ${file.absolutePath} has ${file.length()} bytes" } }
Here is a sample output on my computer:
The file C:/temp/test.txt has 8258 bytes
Reading the contents of a Groovy file as a String is supported by the property text. You just need to read this property to get the contents of the entire file. Here is an example code that reads the content of a Groovy file and prints in to the console:
class FileExample { static void main(String[] args) { File file = new File("C:/temp/rhyme.txt") println "Below is the content of the file ${file.absolutePath}" println file.text } }
Here is the sample output on my computer.
Below is the content of the file C:/temp/rhyme.txt Jack and Jill went up the hill To fetch a pail of water. Jack fell down and broke his crown, And Jill came tumbling after.
If the file you are trying to read is encoded using UTF-8, you can also read a the contents with a simple adjustment of passing the encoding. Here is an example code that reads the contents of a Groovy file as a UTF-8 string:
def fileContents = new File('C:/temp/rhyme_japanese.txt').getText('UTF-8')As you could see, reading contents is very concise in Groovy.
Sometimes we don't want to read the whole file contents into a single String. Sometimes we wish to read the contents line by line. Here is a sample code that reads the contents of a Groovy file line by line. Each line is shown on the screen with the corresponding line number.
class FileExample { static void main(String[] args) { File file = new File("C:/temp/rhyme.txt") println "Below is the content of the file ${file.absolutePath}" def lineNo = 1 def line file.withReader { reader -> while ((line = reader.readLine())!=null) { println "${lineNo}. ${line}" lineNo++ } } } }
Here is the sample output of the code above:
Below is the content of the file C:/temp/rhyme.txt 1. Jack and Jill went up the hill 2. To fetch a pail of water. 3. Jack fell down and broke his crown, 4. And Jill came tumbling after.
If we want full control, we can read all the lines of a file as a list. Here is an example code that reads the contents of a Groovy file and assign the contents to a list.
class FileExample { static void main(String[] args) { File file = new File("C:/temp/rhyme.txt") def lines = file.readLines() println "${file} has ${lines.size()} lines of text" println "Here is the first line: ${lines[0]}" println "Here is the last line: ${lines[lines.size()-1]}" } }
Here is the sample output of the code above:
C:/temp/rhyme.txt has 4 lines of text Here is the first line: Jack and Jill went up the hill Here is the first line: And Jill came tumbling after.
class FileExample { static void main(String[] args) { File file = new File("C:/temp/test.txt") file.write "This is the first line\n" file << "This is the second line\n" file << "This is the third line\n" println file.text } }Here is the sample output of the code fragment above.
This is the first line This is the second line This is the third line
If we built the contents of what we wish to write to a String, we can write the contents in one go! We can assign the value to the text property of a file and it will automatically be written to the file.
class FileExample { static void main(String[] args) { File file = new File("C:/temp/test.txt") file.text = "A\nB\nC" } }
This will be the contents of the file after running the code:
A B C
Here is an example code to test if a Groovy file is a file or directory:
class FileExample { static void main(String[] args) { def file = new File('c:/temp/test.txt') println "File? ${file.isFile()}" println "Directory? ${file.isDirectory()}" } }
Here is a sample output:
File? true Directory? false
Here is a sample code to test if a file is hidden:
class FileExample { static void main(String[] args) { def file = new File('c:/temp/test.txt') println "Hidden? ${file.isHidden()}" } }
Here is a sample output:
Hidden? false
Creating a directory in Groovy is similar to Java. Here is an example code:
class FileExample { static void main(String[] args) { def subdir = new File('c:/temp//test_child_dir') subdir.mkdir() } }
Here is an example code on how to read a text file and copy the contents to another file.
class FileExample { static void main(String[] args) { def src = new File('c:/temp/src.txt') def dst = new File('c:/temp/dst.txt') dst << src.text } }
class FileExample { static void main(String[] args) { def file = new File('c:/temp/test.txt') file.delete() } }
Here is an example code that search for all files given a file name pattern, and then delete them one by one.
class FileExample { static void main(String[] args) { new File("c:/temp").eachFileMatch(~/.*.txt/) { file -> file.delete() } } }
class FileExample { static void main(String[] args) { def file = new File('c:/temp/old_name.txt') file.renameTo( new File('c:/temp/new_name.txt') ) } }
class FileExample { static void main(String[] args) { def rootFiles = new File("test").listRoots() rootFiles.each { file -> println file.absolutePath } } }Here is an example output on a Windows machine:
C:\ D:\Here is an example output on a Linux machine:
/
class FileExample { static void main(String[] args) { new File("c:/temp").eachFile() { file-> println file.getAbsolutePath() } } }Here is a sample output of the code above. Note that both files and subdirectories are listed.
c:\temp\child_dir1 c:\temp\child_dir2 c:\temp\test.txt c:\temp\testing.txt
class FileExample { static void main(String[] args) { new File("c:/temp").eachDir() { file-> println file.getAbsolutePath() } } }Here is a sample output of the code above. Note that only subdirectories are listed.
c:\temp\child_dir1 c:\temp\child_dir2
When a directory structure is deep, it is also possible to read it recursively without using recursion in your code. Just by using the function eachFileRecurse, the list of all files recursively will be returned. Here is an example code on how to list files recursively in Groovy.
class FileExample { static void main(String[] args) { new File("c:/temp").eachFileRecurse() { file-> println file.getAbsolutePath() } } }Here is a sample output of the code above. Note that both files and subdirectories are listed recursively.
c:\temp\child_dir1 c:\temp\child_dir1\grandchild_dir1 c:\temp\child_dir1\grandchild_dir1\a.txt c:\temp\child_dir1\grandchild_dir2 c:\temp\child_dir1\grandchild_dir2\b.txt c:\temp\child_dir2 c:\temp\child_dir2\grandchild2_dir1 c:\temp\child_dir2\grandchild2_dir1\c.txt c:\temp\child_dir2\grandchild2_dir2 c:\temp\child_dir2\grandchild2_dir2\d.txt c:\temp\test.txt c:\temp\testing.txt
class FileExample { static void main(String[] args) { new File("c:/temp").eachDirRecurse() { file-> println file.getAbsolutePath() } } }Here is a sample output of the code above. Note that only subdirectories are listed recursively.
c:\temp\child_dir1 c:\temp\child_dir1\grandchild_dir1 c:\temp\child_dir1\grandchild_dir2 c:\temp\child_dir2 c:\temp\child_dir2\grandchild2_dir1 c:\temp\child_dir2\grandchild2_dir2
class FileExample { static void main(String[] args) { new File("c:/temp").eachFileMatch(~/.*.txt/) { file -> println file.getName() } } }The eachFileMatch matches the file names of the files in the parent directory. This is not recursive.