File

better.files.File
See theFile companion object
class File extends Serializable

Scala wrapper around java.nio.files.Path

Attributes

Companion:
object
Graph
Supertypes
trait Serializable
class Object
trait Matchable
class Any

Members list

Concise view

Value members

Concrete methods

def /(child: String): File

DSL to drop to child

DSL to drop to child

Attributes

def /(child: Symbol): File

DSL to drop to child

DSL to drop to child

Attributes

def addPermission(permission: PosixFilePermission, linkOptions: LinkOptions): File.this.type
def append(text: String, charset: Charset): File.this.type
def appendByteArray(bytes: Array[Byte]): File.this.type
def appendBytes(bytes: Iterator[Byte]): File.this.type
def appendLine(line: String, charset: Charset): File.this.type
def appendLines(lines: Seq[String], charset: Charset): File.this.type

For large number of lines that may not fit in memory, use printLines

For large number of lines that may not fit in memory, use printLines

Attributes

def appendLines(lines: String*): File.this.type

If you need to specify a charset, use the above version

If you need to specify a charset, use the above version

Attributes

def appendText(text: String, charset: Charset): File.this.type
def asynchronousFileChannel(openOptions: OpenOptions): Dispose[AsynchronousFileChannel]
def attributes(linkOptions: LinkOptions): BasicFileAttributes
def bufferedReader(charset: Charset): Dispose[BufferedReader]
def bufferedWriter(charset: Charset, openOptions: OpenOptions): Dispose[BufferedWriter]
def byteArray: Array[Byte]
def bytes: Iterator[Byte]

Attributes

See also:

canonicalFile

def canonicalPath: String

Resolves ../../foo to the fully qualified path

Resolves ../../foo to the fully qualified path

Attributes

def changeExtensionTo(extension: String, linkOptions: LinkOptions): File

Changes the file-extension by renaming this file; if file does not have an extension, it adds the extension Example usage file"foo.java".changeExtensionTo(".scala")

Changes the file-extension by renaming this file; if file does not have an extension, it adds the extension Example usage file"foo.java".changeExtensionTo(".scala")

If file does not exist (or is a directory) no change is done and the current file is returned

Attributes

def chars(charset: Charset): Iterator[Char]

Attributes

Returns:

characters of this file

def checksum(algorithm: MessageDigest, visitOptions: VisitOptions, linkOptions: LinkOptions): String

Attributes

Returns:

checksum of this file (or directory) in hex format

def children: Iterator[File]
def clear(linkOptions: LinkOptions): File.this.type

If this is a directory, remove all its children If its a file, empty the contents

If this is a directory, remove all its children If its a file, empty the contents

Attributes

def collectChildren(matchFilter: File => Boolean, maxDepth: Int, visitOptions: VisitOptions): Iterator[File]

More Scala friendly way of doing Files.walk Note: This is lazy (returns an Iterator) and won't evaluate till we reify the iterator (e.g. using .toList)

More Scala friendly way of doing Files.walk Note: This is lazy (returns an Iterator) and won't evaluate till we reify the iterator (e.g. using .toList)

Attributes

def contains(file: File, strict: Boolean): Boolean

Check if this directory contains this file

Check if this directory contains this file

Attributes

strict

If strict is false, it would return true for self.contains(self)

Returns:

true if this is a directory and it contains this file

def contentAsString(charset: Charset): String

Attributes

Returns:

the content of this file as string

def contentType: Option[String]

return the content type of the file e.g. text/html

return the content type of the file e.g. text/html

Attributes

def copyTo(destination: File, overwrite: Boolean): File

Copy this file to destination similar to unix cp command

Copy this file to destination similar to unix cp command

Attributes

See also:

copyToDirectory() if you want to copy into another directory

def copyTo(destination: File, copyOptions: CopyOptions): File
def copyToDirectory(directory: File, overwrite: Boolean, linkOptions: LinkOptions): File

Copies this file into the given directory

Copies this file into the given directory

Attributes

Returns:

the File referencing the new file created under destination

def createChild(child: String, asDirectory: Boolean, createParents: Boolean, attributes: Attributes, linkOptions: LinkOptions): File
def createDirectories(attributes: Attributes, linkOptions: LinkOptions): File.this.type

Create this directory and all its parents Unlike the JDK, this by default sanely handles the JDK-8130464 bug If you want default Java behaviour, use File.LinkOptions.noFollow

Create this directory and all its parents Unlike the JDK, this by default sanely handles the JDK-8130464 bug If you want default Java behaviour, use File.LinkOptions.noFollow

Attributes

def createDirectory(attributes: Attributes): File.this.type

Create this directory

Create this directory

Attributes

def createDirectoryIfNotExists(createParents: Boolean, attributes: Attributes, linkOptions: LinkOptions): File.this.type
def createFile(attributes: Attributes): File.this.type

Create this file

Create this file

Attributes

def createFileIfNotExists(createParents: Boolean, attributes: Attributes, linkOptions: LinkOptions): File.this.type
def createIfNotExists(asDirectory: Boolean, createParents: Boolean, attributes: Attributes, linkOptions: LinkOptions): File.this.type

Create this file. If it exists, don't do anything

Create this file. If it exists, don't do anything

Attributes

asDirectory

If you want this file to be created as a directory instead, set this to true (false by default)

createParents

If you also want all the parents to be created from root to this file (false by default)

def delete(swallowIOExceptions: Boolean, linkOption: LinkOptions): File.this.type

Deletes this file or directory Unless otherwise specified, this does not follow symlinks i.e. if this is a symlink, only the symlink itself is deleted and not the linked object

Deletes this file or directory Unless otherwise specified, this does not follow symlinks i.e. if this is a symlink, only the symlink itself is deleted and not the linked object

Attributes

swallowIOExceptions

If this is set to true, any exception thrown is swallowed

def deleteOnExit(swallowIOExceptions: Boolean, linkOption: LinkOptions): File.this.type
def digest(algorithm: MessageDigest, visitOptions: VisitOptions, linkOptions: LinkOptions): Array[Byte]
def dosAttributes(linkOptions: LinkOptions): DosFileAttributes
def entries: Iterator[File]
override def equals(obj: Any): Boolean

Compares the receiver object (this) with the argument object (that) for equivalence.

Compares the receiver object (this) with the argument object (that) for equivalence.

Any implementation of this method should be an equivalence relation:

  • It is reflexive: for any instance x of type Any, x.equals(x) should return true.
  • It is symmetric: for any instances x and y of type Any, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any instances x, y, and z of type Any if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

If you override this method, you should verify that your implementation remains an equivalence relation. Additionally, when overriding this method it is usually necessary to override hashCode to ensure that objects which are "equal" (o1.equals(o2) returns true) hash to the same scala.Int. (o1.hashCode.equals(o2.hashCode)).

Attributes

that

the object to compare against this object for equality.

Returns:

true if the receiver object is equivalent to the argument; false otherwise.

Definition Classes
Any
def exists(linkOptions: LinkOptions): Boolean
def extension(includeDot: Boolean, includeAll: Boolean, toLowerCase: Boolean, linkOptions: LinkOptions): Option[String]

Attributes

includeAll

whether all extension tokens should be included, or just the last one e.g. for bundle.tar.gz should it be .tar.gz or .gz

includeDot

whether the dot should be included in the extension or not

toLowerCase

to lowercase the extension or not e.g. foo.HTML should have .html or .HTML

Returns:

extension (including the dot) of this file if it is a regular file and has an extension, else None

def fileChannel(openOptions: OpenOptions, attributes: Attributes): Dispose[FileChannel]
def fileInputStream: Dispose[FileInputStream]
def fileOutputStream(append: Boolean): Dispose[FileOutputStream]
def fileReader: Dispose[FileReader]
def fileWriter(append: Boolean): Dispose[FileWriter]
def glob(pattern: String, includePath: Boolean, maxDepth: Int, syntax: PathMatcherSyntax, visitOptions: VisitOptions): Iterator[File]

Util to glob from this file's path

Util to glob from this file's path

Attributes

includePath

If true, we don't need to set path glob patterns e.g. instead of **.txt we just use *.txt

maxDepth

Recurse up to maxDepth

Returns:

Set of files that matched

def globRegex(pattern: Regex, includePath: Boolean, maxDepth: Int, visitOptions: VisitOptions): Iterator[File]

Util to match from this file's path using Regex

Util to match from this file's path using Regex

Attributes

includePath

If true, we don't need to set path glob patterns e.g. instead of **.txt we just use *.txt

maxDepth

Recurse up to maxDepth

Returns:

Set of files that matched

See also:

glob

def group(linkOptions: LinkOptions): GroupPrincipal
def groupName(linkOptions: LinkOptions): String
def gzipInputStream(bufferSize: Int): Dispose[GZIPInputStream]
def gzipOutputStream(bufferSize: Int, syncFlush: Boolean, append: Boolean): Dispose[GZIPOutputStream]
def gzipTo(destination: File, bufferSize: Int, syncFlush: Boolean, append: Boolean): File
def hasExtension(linkOptions: LinkOptions): Boolean

Returns the extension if file is a regular file If file is unreadable or does not exist, it is assumed to be not a regular file See: https://github.com/pathikrit/better-files/issues/89

Returns the extension if file is a regular file If file is unreadable or does not exist, it is assumed to be not a regular file See: https://github.com/pathikrit/better-files/issues/89

Attributes

override def hashCode: Int

Calculate a hash code value for the object.

Calculate a hash code value for the object.

The default hashing algorithm is platform dependent.

Note that it is allowed for two objects to have identical hash codes (o1.hashCode.equals(o2.hashCode)) yet not be equal (o1.equals(o2) returns false). A degenerate implementation could always return 0. However, it is required that if two objects are equal (o1.equals(o2) returns true) that they have identical hash codes (o1.hashCode.equals(o2.hashCode)). Therefore, when overriding this method, be sure to verify that the behavior is consistent with the equals method.

Attributes

Returns:

the hash code value for this object.

Definition Classes
Any
def inputStream(openOptions: OpenOptions): Dispose[InputStream]
def isChildOf(parent: File): Boolean
def isDirectory(linkOptions: LinkOptions): Boolean

Attributes

Returns:

true if this file (or the file found by following symlink) is a directory

def isEmpty(linkOptions: LinkOptions): Boolean

Attributes

Returns:

true if file is not present or empty directory or 0-bytes file

def isExecutable: Boolean
def isGroupExecutable(linkOptions: LinkOptions): Boolean
def isGroupReadable(linkOptions: LinkOptions): Boolean
def isGroupWritable(linkOptions: LinkOptions): Boolean
def isHidden: Boolean
def isLocked(mode: RandomAccessMode, position: Long, size: Long, isShared: Boolean, linkOptions: LinkOptions): Boolean

Check if a file is locked.

Check if a file is locked.

Attributes

isShared

true to request a shared lock, false to request an exclusive lock.

mode

The random access mode.

position

The position at which the locked region is to start; must be non-negative.

size

The size of the locked region; must be non-negative, and the sum position + size must be non-negative.

Returns:

True if the file is locked, false otherwise.

def isOthersExecutable(linkOptions: LinkOptions): Boolean
def isOthersReadable(linkOptions: LinkOptions): Boolean
def isOthersWritable(linkOptions: LinkOptions): Boolean
def isOwnerExecutable(linkOptions: LinkOptions): Boolean
def isOwnerReadable(linkOptions: LinkOptions): Boolean
def isOwnerWritable(linkOptions: LinkOptions): Boolean
def isParentOf(child: File): Boolean
def isReadLocked(position: Long, size: Long, isShared: Boolean): Boolean
def isReadable: Boolean

This differs from the above as this checks if the JVM can read this file even though the OS cannot in certain platforms

This differs from the above as this checks if the JVM can read this file even though the OS cannot in certain platforms

Attributes

def isRegularFile(linkOptions: LinkOptions): Boolean

Attributes

Returns:

true if this file (or the file found by following symlink) is a regular file

def isSameContentAs(that: File): Boolean

Attributes

Returns:

true if this file is exactly same as that file For directories, it checks for equivalent directory structure

def isSameFileAs(that: File): Boolean
def isSamePathAs(that: File): Boolean
def isSiblingOf(sibling: File): Boolean
def isSimilarContentAs(that: File): Boolean

Almost same as isSameContentAs but uses faster md5 hashing to compare (and thus small chance of false positive) Also works for directories

Almost same as isSameContentAs but uses faster md5 hashing to compare (and thus small chance of false positive) Also works for directories

Attributes

def isWritable: Boolean
def isWriteLocked(position: Long, size: Long, isShared: Boolean): Boolean
def lastModifiedTime(linkOptions: LinkOptions): Instant
def lineCount(charset: Charset): Int

Attributes

Returns:

number of lines in this file

def lineIterator(charset: Charset): Iterator[String]

Iterate over lines in a file (auto-close stream on complete) If you want partial iteration use @see lines()

Iterate over lines in a file (auto-close stream on complete) If you want partial iteration use @see lines()

Attributes

def lines(charset: Charset): Iterable[String]

Load all lines from this file Note: Large files may cause an OutOfMemory in which case, use the streaming version @see lineIterator

Load all lines from this file Note: Large files may cause an OutOfMemory in which case, use the streaming version @see lineIterator

Attributes

Returns:

all lines in this file

def linkTo(destination: File, symbolic: Boolean, attributes: Attributes): File
def list(filter: File => Boolean, maxDepth: Int, visitOptions: VisitOptions): Iterator[File]

List files recursively up to given depth using a custom file filter

List files recursively up to given depth using a custom file filter

Attributes

def list: Iterator[File]
def listRecursively(visitOptions: VisitOptions): Iterator[File]
def listRelativePaths(visitOptions: VisitOptions): Iterator[Path]
def loadBytes: Array[Byte]

load bytes into memory - for large files you want to use @see bytes which uses an iterator

load bytes into memory - for large files you want to use @see bytes which uses an iterator

Attributes

def md5(visitOptions: VisitOptions, linkOptions: LinkOptions): String
def moveTo(destination: File, copyOptions: CopyOptions): File

Move this to destination similar to unix mv command

Move this to destination similar to unix mv command

Attributes

See also:

moveToDirectory() if you want to move into another directory

def moveToDirectory(directory: File, linkOptions: LinkOptions): File

Moves this file into the given directory

Moves this file into the given directory

Attributes

Returns:

the File referencing the new file created under destination

def name: String

Name of file Certain files may not have a name e.g. root directory - returns empty string in that case

Name of file Certain files may not have a name e.g. root directory - returns empty string in that case

Attributes

def nameOption: Option[String]

Certain files may not have a name e.g. root directory - returns None in that case

Certain files may not have a name e.g. root directory - returns None in that case

Attributes

Return the file name without extension e.g. for foo.tar.gz return foo

Return the file name without extension e.g. for foo.tar.gz return foo

Attributes

def nameWithoutExtension(includeAll: Boolean, linkOptions: LinkOptions): String

Attributes

includeAll

For files with multiple extensions e.g. "bundle.tar.gz" nameWithoutExtension(includeAll = true) returns "bundle" nameWithoutExtension(includeAll = false) returns "bundle.tar"

def newAsynchronousFileChannel(openOptions: OpenOptions): AsynchronousFileChannel
def newBufferedReader(charset: Charset): BufferedReader
def newBufferedWriter(charset: Charset, openOptions: OpenOptions): BufferedWriter
def newFileChannel(openOptions: OpenOptions, attributes: Attributes): FileChannel
def newFileInputStream: FileInputStream
def newFileOutputStream(append: Boolean): FileOutputStream
def newFileReader: FileReader
def newFileWriter(append: Boolean): FileWriter
def newGzipInputStream(bufferSize: Int): GZIPInputStream
def newGzipOutputStream(bufferSize: Int, syncFlush: Boolean, append: Boolean): GZIPOutputStream
def newInputStream(openOptions: OpenOptions): InputStream
def newOutputStream(openOptions: OpenOptions): OutputStream
def newPrintWriter(autoFlush: Boolean, openOptions: OpenOptions): PrintWriter
def newRandomAccess(mode: RandomAccessMode): RandomAccessFile
def newScanner(splitter: StringSplitter, charset: Charset): Scanner
def newWatchService: WatchService
def newZipInputStream(charset: Charset): ZipInputStream
def newZipOutputStream(openOptions: OpenOptions, charset: Charset): ZipOutputStream
def nonEmpty(linkOptions: LinkOptions): Boolean

Attributes

Returns:

for directories, true if it has no children, false otherwise for files, true if it is a 0-byte file, false otherwise else true if it exists, false otherwise

def notExists(linkOptions: LinkOptions): Boolean
def outputStream(openOptions: OpenOptions): Dispose[OutputStream]
def overwrite(text: String, openOptions: OpenOptions, charset: Charset): File.this.type
def owner(linkOptions: LinkOptions): UserPrincipal
def ownerName(linkOptions: LinkOptions): String

Return parent of this file NOTE: This API returns null if this file is the root; please use parentOption if you expect to handle roots

Return parent of this file NOTE: This API returns null if this file is the root; please use parentOption if you expect to handle roots

Attributes

def parentOption: Option[File]

Attributes

Returns:

Some(parent) of this file or None if this is the root and thus has no parent

def pathAsString: String
def pathMatcher(syntax: PathMatcherSyntax, includePath: Boolean)(pattern: String): PathMatcher
def permissions(linkOptions: LinkOptions): Set[PosixFilePermission]
def permissionsAsString(linkOptions: LinkOptions): String
def posixAttributes(linkOptions: LinkOptions): PosixFileAttributes
def printLines(lines: IterableOnce[_], openOptions: OpenOptions): File.this.type

Write lines into this file

Write lines into this file

Attributes

def printWriter(autoFlush: Boolean, openOptions: OpenOptions): Dispose[PrintWriter]
def randomAccess(mode: RandomAccessMode): Dispose[RandomAccessFile]
def readDeserialized[A](classLoaderOverride: Option[ClassLoader], bufferSize: Int, openOptions: OpenOptions): A

Deserialize a object using Java's default serialization from this file

Deserialize a object using Java's default serialization from this file

Attributes

def register(service: WatchService, events: Events): File.this.type

register a watch service for given events

register a watch service for given events

Attributes

def relativize(destination: File): Path
def removePermission(permission: PosixFilePermission, linkOptions: LinkOptions): File.this.type
def renameTo(newName: String): File

getResource... always uses "/" for separator https://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)

def root: File

Attributes

Returns:

root of this file e.g. '/' for '/dve/null'

def scanner(splitter: StringSplitter, charset: Charset): Dispose[Scanner]
def setGroup(group: String, linkOptions: LinkOptions): File.this.type
def setOwner(owner: String): File.this.type
def setPermissions(permissions: Set[PosixFilePermission]): File.this.type
def sha1(visitOptions: VisitOptions, linkOptions: LinkOptions): String
def sha256(visitOptions: VisitOptions, linkOptions: LinkOptions): String
def sha512(visitOptions: VisitOptions, linkOptions: LinkOptions): String
def sibling(name: String): File
def siblings: Iterator[File]
def size(returnZeroIfMissing: Boolean, visitOptions: VisitOptions): Long

Attributes

returnZeroIfMissing

If true, return zeroes for missing files*

Returns:

file size (for directories, return size of the directory) in bytes

def streamedUnzip(destinationDirectory: File, charset: Charset): File

Streamed unzipping is slightly slower but supports larger files and more encodings

Streamed unzipping is slightly slower but supports larger files and more encodings

Attributes

destinationDirectory

destination folder; Creates this if it does not exist

Returns:

The destination where contents are unzipped

See also:
def symbolicLinkTo(destination: File, attributes: Attributes): File
def testPermission(permission: PosixFilePermission, linkOptions: LinkOptions): Boolean

test if file has this permission

test if file has this permission

Attributes

def toJava: File

Attributes

Returns:

java.io.File version of this

override def toString: String

Returns a string representation of the object.

Returns a string representation of the object.

The default representation is platform dependent.

Attributes

Returns:

a string representation of the object.

Definition Classes
Any

Java's temporary files/directories are not cleaned up by default. If we explicitly call .deleteOnExit(), it gets added to shutdown handler which is not ideal for long running systems with millions of temporary files as: a) it would slowdown shutdown and b) occupy unnecessary disk-space during app lifetime

Java's temporary files/directories are not cleaned up by default. If we explicitly call .deleteOnExit(), it gets added to shutdown handler which is not ideal for long running systems with millions of temporary files as: a) it would slowdown shutdown and b) occupy unnecessary disk-space during app lifetime

This util auto-deletes the resource when done using the Dispose facility

Example usage: File.temporaryDirectory().foreach(tempDir => doSomething(tempDir)

Attributes

def tokens(splitter: StringSplitter, charset: Charset): Iterator[String]

Similar to string.split(), this returns tokens from the file by given splitter (default is whitespace)

Similar to string.split(), this returns tokens from the file by given splitter (default is whitespace)

Attributes

def touch(time: Instant, attributes: Attributes, linkOptions: LinkOptions): File.this.type

Similar to the UNIX command touch - create this file if it does not exist and set its last modification time

Similar to the UNIX command touch - create this file if it does not exist and set its last modification time

Attributes

def unGzipTo(destination: File, append: Boolean, bufferSize: Int): File
def unzip(zipFilter: ZipEntry => Boolean, charset: Charset): File

unzip to a temporary zip file

unzip to a temporary zip file

Attributes

Returns:

the zip file

def unzipTo(destination: File, zipFilter: ZipEntry => Boolean, charset: Charset, safeUnzip: Boolean): File

Unzips this zip file

Unzips this zip file

Attributes

charset

Optional charset parameter

destination

destination folder; Creates this if it does not exist

safeUnzip

Optional parameter to set whether unzipTo should unzip entries containing directory traversal characters to directories outside the destination

zipFilter

An optional param to reject or accept unzipping a file

Returns:

The destination where contents are unzipped

def update(attribute: String, value: Any, linkOptions: LinkOptions): File.this.type

Set a file attribute e.g. file("dos:system") = true

Set a file attribute e.g. file("dos:system") = true

Attributes

def uri: URI
def url: URL
def usingLock[U](mode: RandomAccessMode)(f: FileChannel => U): U
def verifiedExists(linkOptions: LinkOptions): Option[Boolean]

Attributes

Returns:

Some(true) if file is guaranteed to exist Some(false) if file is guaranteed to not exist None if the status is unknown e.g. if file is unreadable

See also:
def walk(maxDepth: Int, visitOptions: VisitOptions): Iterator[File]

Walk the directory tree recursively upto maxDepth

Walk the directory tree recursively upto maxDepth

Attributes

Returns:

List of children in BFS maxDepth level deep (includes self since self is at depth = 0)

def watchService: Dispose[WatchService]
def write(text: String, openOptions: OpenOptions, charset: Charset): File.this.type
def writeByteArray(bytes: Array[Byte], openOptions: OpenOptions): File.this.type

Write byte array to file. For large contents consider using the writeBytes

Write byte array to file. For large contents consider using the writeBytes

Attributes

def writeBytes(bytes: Iterator[Byte], openOptions: OpenOptions): File.this.type
def writeSerialized(obj: Serializable, bufferSize: Int, openOptions: OpenOptions): File.this.type

Serialize a object using Java's serializer into this file, creating it and its parents if they do not exist

Serialize a object using Java's serializer into this file, creating it and its parents if they do not exist

Attributes

def writeText(text: String, openOptions: OpenOptions, charset: Charset): File.this.type
def zip(compressionLevel: Int, charset: Charset): File

zip to a temp directory

zip to a temp directory

Attributes

Returns:

the target directory

def zipIn(files: Iterator[File], compressionLevel: Int, charset: Charset): File.this.type

Adds these files into this zip file Example usage: File("test.zip").zipIn(Seq(file"hello.txt", file"hello2.txt"))

Adds these files into this zip file Example usage: File("test.zip").zipIn(Seq(file"hello.txt", file"hello2.txt"))

Attributes

def zipInputStream(charset: Charset): Dispose[ZipInputStream]
def zipOutputStream(openOptions: OpenOptions, charset: Charset): Dispose[ZipOutputStream]
def zipTo(destination: File, compressionLevel: Int, charset: Charset): File

Zips this file (or directory)

Zips this file (or directory)

Attributes

destination

The destination file; Creates this if it does not exists

Returns:

The destination zip file

Concrete fields

val path: Path

Implicits

Implicits

implicit val fileSystem: FileSystem