Skip to content

File Wrapper

FileWrapper

Provides utility methods for manipulating a File. On the following methods, wrap is a FileWrapper.

Tip

  • to convert the File to a string, use the toString method or define the variable as a String

Reading

get

Retrieves the wrapped File

Syntax
File wrap.get()

Example

final value = p6.wrap.of '/path/to.ext' asFile() get()

toString

Retrieves the String representation of the wrapped value using the optional number format.

Syntax
String wrap.toString()

Example

final s = p6.wrap.of p6.uri.fileFromUrl('p6file:///path/to.ext') toString()
final String s = p6.wrap.of p6.uri.fileFromUrl('p6file:///path/to.ext')

Path parts

extension

Retrieves the extension of the file.

Syntax
StringWrapper wrap.extension()

Example

final String value = p6.wrap.of '/path/to.ext' asFile() extension()
assert value == 'ext'

name

Retrieves the name of the file.

Syntax
StringWrapper wrap.name()

Example

final String value = p6.wrap.of '/path/to.ext' asFile() name()
assert value == 'to.ext'

baseName

Retrieves the base name of the file.

Syntax
StringWrapper wrap.baseName()

Example

final String value = p6.wrap.of '/path/to.ext' asFile() baseName()
assert value == 'to'

Metadata

New Feature

Since 6.10.24

exists / isFile / isDirectory

Read-only checks against the filesystem.

Syntax
boolean wrap.exists()
boolean wrap.isFile()
boolean wrap.isDirectory()

Example

final value = p6.wrap.of '/opt/path/to.ext' asFile() exists()

size

Returns the file size in bytes (0 when the file does not exist).

Syntax
NumberWrapper wrap.size()

Example

final bytes = p6.wrap.of '/opt/path/to.ext' asFile() size() get()

lastModified

Returns the last-modified time as a DateWrapper.

Syntax
DateWrapper wrap.lastModified()

Example

final recent = p6.wrap.of('/opt/path/to.ext').asFile().lastModified().isAfter(p6.wrap.now().add('-1d').get())

Conversions

New Feature

Since 6.10.24

asString

Returns the absolute path as a StringWrapper.

Syntax
StringWrapper wrap.asString()

Example

final String value = p6.wrap.of '/opt/path/to.ext' asFile() asString()
assert value == '/opt/path/to.ext'

asUri

Returns the file location as a URI string.

Syntax
StringWrapper wrap.asUri()

Example

final String value = p6.wrap.of '/opt/path/to.ext' asFile() asUri()
assert value == 'file:/opt/path/to.ext'

Combined example

Break a path into its parts, then read metadata from the filesystem.

final f = p6.wrap.of('/opt/data/invoice-42.xml').asFile()

assert f.name() == 'invoice-42.xml'
assert f.baseName() == 'invoice-42'
assert f.extension() == 'xml'

// filesystem-backed (at runtime):
if (f.exists() && f.isFile()) {
    log.info "${f.name()} — ${f.size().asFileSize()}"   // e.g. "invoice-42.xml — 12.4 KB"
}