RSS

Groovy File Examples

15 Mar

 2000px-Groovy-logo.svgFile processing is one of the most common task in programming. Fortunately, Groovy makes file manipulation easier. Things that are long and complicated in Java are now very much concise in Groovy. Here are some Groovy File programming examples.

Introduction

The beauty of working with files in groovy is not needing to work with so many different interfaces and classes. For example, we don’t need this code to read a file:

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.

Get File Size

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

Read Contents As String

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.

Read Contents line by line

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.

Read Contents To A List

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.

Write To File

There are multiple ways on how we can write to a file. Below is an example code that writes contents to a file using the write method and the left shift operator. Note that you need to add a line feed at the end of each line because both write and left shift don’t append a new line at the end.

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

Test if File or Directory

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

Test if File is Hidden

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

Create Directory

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()
   }
}

Copy File Contents

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
   }
}

Delete File

Deleting a file in Groovy is similar on how it is done in Java. Here is a simple example that deletes a single file:

class FileExample {
   static void main(String[] args) {
      def file = new File('c:/temp/test.txt')
      file.delete()
   }
}

Delete Multiple Files

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()
      }
   }
}

Rename a File

Renaming a file in Groovy is similar on how it is done in Java. Here is a simple example that renames a single file:

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') )
   }
}

Listing Files

Here are some scenarios on how we can list files and directories in Groovy. Groovy file has convenience methods to help simplify code:

  • Listing Root File System

    Below is an example code on how we could list file system roots on a machine.

    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:

    /
  • List Files and Subdirectories

    Here is an example code on how to list all files and subdirectories of a parent directory in Groovy .

    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
  • List Subdirectories Only

    If we want to list only subdirectories of a parent directory, the eachDir() function can be used. Here is an example code on how to list only subdirectories of a parent directory in Groovy .

    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
  • List Files and Subdirectories Recursively

    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
  • List Subdirectories Only Recursively

    There is also a convenience function if we want to list all subdirectories recursively. Here is an example code on how to list directories only recursively in Groovy.

    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
  • Search File Name Pattern

    Here is an example code on how to search for file pattern. E.g. search for all text files.

    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.

Advertisements
 
Leave a comment

Posted by on 15/03/2016 in Jmeter

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: