Groovy is widely used as a scripting language for automating repetitive tasks. While working with files, it occurs sometime that one has to change the attributes of a file in Windows. For example, you may need to set the file as read-only, archived, and so on.
In this recipe, we will learn how to change file attributes in Windows using Groovy.
Let's start by creating a file and adding some content to it. Open your shell, start groovysh
and type the following code:
f = new File('test.txt') f << 'hello, this is a test file'
You should now see a file named test.txt
in the same directory where you started groovysh
.
On a DOS console, type:
attrib test.txt
The output should be as follows:
A I C:hello.txt
The initial on the left stands for the first letter of the enabled attribute: A
for "archive", S
for "system", H
for "hidden" and R
for "read-only".
With the exclusion of the read-only attribute; in Java, there is no way to set the Windows file attributes through the File API. To make a file read-only:
f.setReadOnly()
This will change the R
attribute:
attrib test.txt A R I C:hello.txt
execute
method of String
. The external process is the attrib
DOS command that can be used to set and read file attributes.'attrib +H C:/hello.txt'.execute()
'attrib -H C:/hello.txt'.execute()
Groovy provides a simple way to execute command line processes. Simply write the command line as a string and call the execute
method. The execute
method returns a java.lang.Process
instance, which will subsequently allow the in
/err
/outstreams
to be processed and the exit value from the process to be inspected.
This snippet executed from groovish
will output the directory listing on a UNIX machine:
println 'ls -al'.execute().text
Alternatively, we can access the stream resulting from the process and print the result line-by-line:
p = 'ls -al'.execute().text p.in.eachLine { line -> print line }
If you run Groovy using JDK 7, you can leverage the new NIO API to set the Windows file attributes. The following example shows you how to do it:
import java.nio.file.* import java.nio.file.attribute.* def f = new File('hello.txt') f << 'hello, hello' def path = Paths.get('C:\groovybook\hello.txt') def dosView = Files.getFileAttributeView( path, DosFileAttributeView ) dosView.hidden = true dosView.archive = true dosView.system = true
This code will fail if it is executed in an environment other than Windows.