`
wenson
  • 浏览: 1051069 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Groovy文件操作

 
阅读更多

To see the OS-dependent characters used for formatting filenames (here, when running on Windows):


assert File.separator == '\\' && File.separatorChar == '\\' as char
    //used for formatting file names
assert File.pathSeparator == ';' && File.pathSeparatorChar == ';' as char

Instances of File are immutable representations of objects in the file system, that may or may not exist. To see different formats of a filename (here, when running within D:\Groovy\Scripts directory):


def f= new File('File.txt') //relative file name
assert f.name == 'File.txt'
assert ! f.isAbsolute()
assert f.path == 'File.txt'
assert f.parent == null
assert f.absolutePath == 'D:\\Groovy\\Scripts\\File.txt' //returns a string
assert f.absoluteFile.toString() == 'D:\\Groovy\\Scripts\\File.txt'
    //returns a File object instead of string
assert f.canonicalPath == 'D:\\Groovy\\Scripts\\File.txt'
assert f.canonicalFile.toString() == 'D:\\Groovy\\Scripts\\File.txt'
    //returns a File object instead of string
assert f.toURI().toString() == 'file:/D:/Groovy/Scripts/File.txt'
    //toURI() returns a URI object

f= new File('D:/Groovy/Scripts/File.txt') //absolute file name
assert f.name == 'File.txt'
assert f.isAbsolute()
assert f.path == 'D:\\Groovy\\Scripts\\File.txt'
assert f.parent == 'D:\\Groovy\\Scripts'
assert f.parentFile.toString() == 'D:\\Groovy\\Scripts'
    //returns a File object instead of string
assert f.absolutePath == 'D:\\Groovy\\Scripts\\File.txt'
assert f.canonicalPath == 'D:\\Groovy\\Scripts\\File.txt'

f= new File('../File.txt')
assert f.name == 'File.txt'
assert ! f.isAbsolute()
assert f.path == '..\\File.txt'
assert f.parent == '..'
assert f.absolutePath == 'D:\\Groovy\\Scripts\\..\\File.txt'
assert f.canonicalPath == 'D:\\Groovy\\File.txt'

f= new File('') //current directory
assert f.name == ''
assert ! f.isAbsolute()
assert f.path == ''
assert f.parent == null
assert f.absolutePath == 'D:\\Groovy\\Scripts'
assert f.canonicalPath == 'D:\\Groovy\\Scripts'

assert new File('File.txt') == new File('File.txt')
    //compares two filenames' lexical names
assert new File('File.txt').compareTo(new File('File.txt')) == 0
    //equivalent method name
assert new File('File.txt') != new File('../Scripts/File.txt')
    //lexical names different (although files are the same)

None of the above example's files were created. Files are only created by some event:


def f1= new File('File1.txt')
f1 << 'abcdefg'
    //file created by writing to it; file appended to if it already exists
assert f1.length() == 7 && f1.size() == 7
assert f1.isFile() && ! f1.isDirectory() && ! f1.isHidden()

def f2= new File('D:/Groovy/Scripts', 'File2.txt')
    //we can optionally supply the parent, either as a string...
f2= new File(new File('D:/Groovy/Scripts'), 'File2.txt')
    //...or as a File object
assert ! f2.exists()
f2.createNewFile() //if it doesn't already exist
assert f2.exists()

def d1= new File('Directory1')
d1.mkdir() //make directory, if it doesn't already exist
def d2= new File('Directory2/SubDir1')
d2.mkdirs()
    //make directory, including necessary but nonexistent parent directories

println f1.getFreeSpace()
    //the number of unallocated bytes in the partition this abstract file is in
println f1.getUsableSpace()
    //the number of bytes available to this virtual machine in the partition
    //this abstract file is in
println f1.getTotalSpace() //the size of the partition this abstract file is in


//We can set file permissions:

assert f2.setWritable(true, false) && f2.canWrite()
    //set writable permission for every user
assert f2.setWritable(true) && f2.canWrite()
    //set writable permission on file for owner only
assert f2.setWritable(false, false) && ! f2.canWrite()
    //unset writable permission for every user
assert f2.setWritable(false) && ! f2.canWrite()
    //unset writable permission on file for owner only
f2.writable= true //property format for owner only
assert f2.canWrite()

assert f2.setReadOnly() && ! f2.canWrite()
assert f2.setExecutable(true, false) && f2.canExecute()
    //set executable permission for every user
assert f2.setExecutable(true) && f2.canExecute()
    //set executable permission on file for owner only
f2.executable= true //property format for owner only
assert f2.canExecute()
assert ! f2.setExecutable(false)
    //returns false because command unsuccessful: can't make file
    //nonexecutable on Windows, though can on other systems

assert f2.setReadable(true, false) && f2.canRead()
    //set readable permission for every user
assert f2.setReadable(true) && f2.canRead()
    //set readable permission on file for owner only
f2.readable= true //property format for owner only
assert f2.canRead()
assert ! f2.setReadable(false)
    //can't make file nonreadable on Windows


//We can retrieve a list of files from a directory:

assert new File('D:/Groovy/Scripts').list().toList() ==
  ['Script.bat', 'File1.txt', 'File2.txt', 'Directory1', 'Directory2']
    //list() returns an array of strings

assert new File('Directory2').list().toList() == ['SubDir1']
assert new File('').list() == null
    //list() returns null if directory not explicitly specified

assert new File('D:/Groovy/Scripts').list(
    [accept:{d, f-> f ==~ /.*?1.*/ }] as FilenameFilter
  ).toList() == ['File1.txt', 'Directory1']
    //filter taking dir (File) and file (String) arguments, returns boolean

assert new File('D:/Groovy/Scripts').list(
    {d, f-> f ==~ /.*?1.*/ } as FilenameFilter
  ).toList() == ['File1.txt', 'Directory1'] //shorter syntax

assert new File('D:/Groovy/Scripts').listFiles().toList()*.name ==
  ['Script.bat', 'File1.txt', 'File2.txt', 'Directory1', 'Directory2']
    //listFiles() returns array of File objects

assert new File('Directory2').listFiles().toList()*.toString() ==
  ['Directory2\\SubDir1']

assert new File('D:/Groovy/Scripts').listFiles(
    {dir, file-> file ==~ /.*?\.txt/ } as FilenameFilter
  ).toList()*.name == [ 'File1.txt', 'File2.txt' ]

assert new File('D:/Groovy/Scripts').listFiles(
    [accept:{file-> file ==~ /.*?\.txt/ }] as FileFilter
  ).toList()*.name == [ 'File1.txt', 'File2.txt' ]
    //use a filter taking one argument only, returning boolean


//Renaming and deleting files:

f2.renameTo( new File('RenamedFile2.txt') )
assert f2.name == 'File2.txt' //because File object is immutable
assert new File('RenamedFile2.txt').exists()

[new File('RenamedFile2.txt'), new File('Directory1'), new File('Directory2')].
    each{ it.delete() } //delete files
assert ! new File('RenamedFile2.txt').exists()
assert ! new File('Directory1').exists()
assert new File('Directory2').exists()
    //because each sub-directory must be deleted separately

assert new File('Directory2/SubDir1').delete() //returns true if file deleted OK
assert new File('Directory2').delete()
assert ! new File('Directory2').exists()

new File('File1.txt').deleteOnExit()
assert new File('File1.txt').exists() //but will be deleted when VM exits

def mod= new File('File1.txt').lastModified()
assert new File('File1.txt').setLastModified(mod - 60000)
    //60 seconds previously, returns true if successful
new File('File1.txt').lastModified= mod - 120000
    //property syntax for setting only
assert new File('File1.txt').lastModified() == mod - 120000

To perform general file manipulation in a file system, we can retrieve all the topmost directories:


println File.listRoots().toList()*.toString()
    //listRoots() returns an array of File objects

To create a temporary file, with given prefix (of at least 3 chars) and suffix:


File.createTempFile('Tem', '.txt')
    //created in directory for temporary files
File.createTempFile('Tem', '.txt', new File('D:\\Groovy\\Scripts'))
    //eg, created D:/Groovy/Scripts/Tem59217.txt

We can read and write to files in various ways, as in this example:


def f1= new File('File1.txt') << 'abcdefg:hijklmnop:qrstuv:wxyz\n'
    //create and write to the file
f1.leftShift('123:456:7890\n') //equivalent method name
new File('File2.txt').createNewFile()
[new File('Directory1'), new File('Directory2/SubDir1')].each{ it.mkdirs() }

def list= []
new File('D:\\Groovy\\Scripts').eachFile{ list<< it.name }
    //eachFile() returns a list of File objects
assert list ==
    ['Script.bat', 'File1.txt', 'File2.txt', 'Directory1', 'Directory2']

list= []
new File('D:\\Groovy\\Scripts').eachFileMatch(~/File.*?\.txt/){ list<< it.name }
    //a regular expression, or any caseable expression
assert list == ['File1.txt', 'File2.txt']

list= []
new File('D:\\Groovy\\Scripts').eachFileRecurse{ list<< it.name }
assert list == ['Script.bat', 'File1.txt', 'File2.txt',
                'Directory1', 'Directory2', 'SubDir1']

list= []
new File('D:\\Groovy\\Scripts').eachDir{ list<< it.name }
assert list == ['Directory1', 'Directory2']

list= []
f1.eachLine{ list<< it }
assert list == [ 'abcdefg:hijklmnop:qrstuv:wxyz', '123:456:7890' ]

list= f1.readLines()
assert list == [ 'abcdefg:hijklmnop:qrstuv:wxyz', '123:456:7890' ]

list= []
f1.splitEachLine(':'){ list<< it } //splits each line into a list
assert list == [
  ['abcdefg', 'hijklmnop', 'qrstuv', 'wxyz'],
  ['123', '456', '7890'],
]

def f2= new File('File2.txt')
f2.write('abcdefg\n') //can only write strings
assert f2.getText() == 'abcdefg\n'
f2.append('hijklmnop,')
f2.append(42) //can append any object
assert f2.getText() == '''abcdefg
hijklmnop,42'''

f2.write('???????????????', 'unicode') //overwrites existing contents
assert f2.getText('unicode') == '???????????????'
f2.append('???????????????', 'unicode') //also appends unicode marker 0xFEFF
assert f2.getText('unicode') == '???????????????' + (0xFEFF as char) + '???????????????'

[ new File('File1.txt'),
  new File('File2.txt'),
  new File('Directory1'),
  new File('Directory2/SubDir1'),
  new File('Directory2'),
].each{ it.delete() } //delete files used by this example
from:http://groovy.codehaus.org/JN2015-Files
分享到:
评论

相关推荐

    深入探索Groovy脚本:文件操作的艺术

    Groovy,作为一种动态语言,以其简洁的语法和强大的功能在Java虚拟机(JVM)上运行,为文件操作提供了一个非常灵活和强大的工具。本文将深入探讨如何使用Groovy脚本进行文件操作,包括文件的创建、读取、写入、删除...

    微服务项目中添加groovy文件技巧.docx

    然而,在实际操作中,直接在微服务项目中添加.Groovy文件会面临一些挑战。比如,当我们在代码中引入一个新的对象时,由于IDE(如Eclipse)无法识别到该对象所依赖的包,会出现编译器报错,对象下方会显示一条波浪线...

    Java IO流和文件操作实现过程解析

    Java IO流和文件操作实现过程解析 Java IO流和文件操作实现过程解析是Java语言中的一种基本操作,IO流是Java中处理输入输出的基础。Java中的IO流主要包括两种类型:字节流和字符流。字节流用于处理二进制数据,而...

    groovy模板

    6. **文件操作** Groovy提供了简单的方法来处理文件和目录。这些Groovy文件可能包含了读取、写入、移动或操作其他文件的代码,如`Guangfa201602.groovy`可能涉及广发银行2016年2月的数据处理。 综上所述,这个...

    eclipse安装groovy插件的步骤

    通过上述步骤,您已经完成了在 Eclipse 中安装 Groovy 插件的过程,并学会了如何使用 Groovy 进行基本的编程操作。Groovy 是一种灵活且功能强大的脚本语言,非常适合用于自动化任务、单元测试以及快速应用开发等领域...

    groovy-2.3.6-installer

    通过执行这个exe文件,用户可以在系统上快速配置好Groovy环境,包括设置PATH变量、安装Groovy解释器和相关工具。安装过程中,用户可以选择自定义安装路径,以便更好地管理开发环境。 安装Groovy后,开发者可以使用...

    groovy脚本实现对数据库的增删改查

    在IT行业中,Groovy常被用于快速开发、脚本编写以及自动化任务,尤其在处理数据库操作时,其简洁的语法使得数据库的增删改查(CRUD)变得更加高效。 在“groovy脚本实现对数据库的增删改查”这个主题中,我们将深入...

    groovy-sdk-4.0.3

    3. **标准库**:Groovy SDK附带了一套丰富的标准库,包含各种实用的类和函数,如文件操作、网络通信、日期和时间处理等。 4. **GroovyShell**和**GroovyConsole**:这两个工具分别用于交互式地运行Groovy脚本和提供...

    groovy速查手册

    - **脚本编辑与执行**:通过`groovy-i`命令可以对文本文件进行行内编辑,并保存原始文件的备份。 - **类与脚本**:Groovy中的类声明与Java类似,默认访问修饰符为public。同时,Groovy支持定义脚本并使用`...

    groovy-all-2.4.8.jar

    - 可以编写Groovy脚本文件(`.groovy`),然后通过GroovyShell或GroovyScriptEngine来运行。 - 对于构建工具,如Maven或Gradle,可以通过配置依赖项来使用这个版本的Groovy。 5. **Groovy的应用场景** - **脚本...

    apache-groovy-sdk-4.0.1下载

    6. **bin目录下的脚本**:每个脚本都有相应的Windows批处理文件(.bat)和Unix/Linux shell脚本(.sh),确保在不同操作系统上都能正常工作。 Apache Groovy提供了一些独特的特性,例如: - **简洁的语法**:...

    groovy-api-chm

    "groovy-api-1.7.2.chm" 文件包含了Groovy核心API的详细文档,涵盖了Groovy的基础类、语法特性、内置类型以及各种操作符。这些API包括了GroovyObject接口,它是所有Groovy类的基类,提供了诸如`invokeMethod`和`...

    groovy常用Script

    4. **目录操作**:`directory_01.groovy` 可能包含了处理文件系统目录的代码,Groovy提供了一系列的类和方法来操作文件和目录,如`java.io.File`和`java.nio.file`包。 5. **字符串操作**:`string_01.groovy` 可能...

    实战groovy.rar

    4. 文件I/O和网络编程:学习如何使用Groovy进行文件操作和网络通信。 5. 测试与调试:掌握Spock测试框架,进行单元测试和集成测试。 6. 深入理解Groovy与Java的互操作性,以便在既有Java项目中无缝引入Groovy。 五...

    Groovy Language Documentation Version 2.5.5

    Groovy 2.5.5版本的官方文档是一个详细的手册,其内容涵盖了从基础语法到高级特性,包括语言规范、程序结构、操作符、对象导向编程和类型系统等方面。以下是对文档内容的详细解读: 1. Groovy语言规范(Groovy ...

    Groovy安装以及简单使用

    在Groovy中,`each`方法接收一个闭包作为参数,这个闭包对数组中的每个元素进行操作。上面的代码会打印出每个数字的两倍值。 Groovy与Java的集成非常紧密,可以通过`@groovy.transform.CompileStatic`注解实现静态...

Global site tag (gtag.js) - Google Analytics