CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlin--kotlin-stdlib-jdk7

Kotlin Standard Library JDK 7 extension providing Path utilities and platform-specific implementations for Java NIO and JDK 7+ features

Pending
Overview
Eval results
Files

file-system.mddocs/

File System Operations

File and directory operations including existence checks, creation, deletion, copying, moving, and comprehensive attribute management for robust file system interactions.

Capabilities

Existence and Type Checking

Check file existence and determine file types with optional link handling.

/**
 * Checks if the file located by this path exists.
 * @return true if the file definitely exists, false otherwise
 */
fun Path.exists(vararg options: LinkOption): Boolean

/**
 * Checks if the file located by this path does not exist.
 * @return true if the file definitely does not exist, false otherwise
 */
fun Path.notExists(vararg options: LinkOption): Boolean

/**
 * Checks if the file located by this path is a regular file.
 */
fun Path.isRegularFile(vararg options: LinkOption): Boolean

/**
 * Checks if the file located by this path is a directory.
 */
fun Path.isDirectory(vararg options: LinkOption): Boolean

/**
 * Checks if the file located by this path exists and is a symbolic link.
 */
fun Path.isSymbolicLink(): Boolean

Usage Examples:

import kotlin.io.path.*
import java.nio.file.LinkOption
import java.nio.file.Paths

val path = Paths.get("/home/user/document.pdf")

if (path.exists()) {
    when {
        path.isRegularFile() -> println("It's a regular file")
        path.isDirectory() -> println("It's a directory")
        path.isSymbolicLink() -> println("It's a symbolic link")
    }
} else {
    println("File does not exist")
}

// Check without following symbolic links
val link = Paths.get("/home/user/link-to-file")
val isLinkWithoutFollowing = link.isSymbolicLink()
val existsWithoutFollowing = link.exists(LinkOption.NOFOLLOW_LINKS)

Permission and Property Checking

Check file permissions and properties with system-specific handling.

/**
 * Checks if the file located by this path exists and is executable.
 */
fun Path.isExecutable(): Boolean

/**
 * Checks if the file located by this path is considered hidden.
 * This check is dependent on the current filesystem.
 */
fun Path.isHidden(): Boolean

/**
 * Checks if the file located by this path exists and is readable.
 */
fun Path.isReadable(): Boolean

/**
 * Checks if the file located by this path exists and is writable.
 */
fun Path.isWritable(): Boolean

/**
 * Checks if the file located by this path points to the same file or directory as other.
 */
fun Path.isSameFileAs(other: Path): Boolean

Usage Examples:

import kotlin.io.path.*
import java.nio.file.Paths

val scriptFile = Paths.get("/usr/local/bin/my-script.sh")

// Check permissions
val permissions = listOf(
    "readable" to scriptFile.isReadable(),
    "writable" to scriptFile.isWritable(),
    "executable" to scriptFile.isExecutable(),
    "hidden" to scriptFile.isHidden()
)

permissions.forEach { (perm, hasIt) ->
    println("$perm: $hasIt")
}

// Check if two paths point to the same file
val originalFile = Paths.get("/home/user/original.txt")
val linkFile = Paths.get("/home/user/link-to-original.txt")
if (originalFile.isSameFileAs(linkFile)) {
    println("Both paths point to the same file")
}

File and Directory Creation

Create files and directories with optional attributes and parent directory handling.

/**
 * Creates a new and empty file specified by this path, failing if the file already exists.
 */
fun Path.createFile(vararg attributes: FileAttribute<*>): Path

/**
 * Creates a new directory or throws an exception if there is already a file or directory located by this path.
 * Note that the parent directory where this directory is going to be created must already exist.
 */
fun Path.createDirectory(vararg attributes: FileAttribute<*>): Path

/**
 * Creates a directory ensuring that all nonexistent parent directories exist by creating them first.
 * If the directory already exists, this function does not throw an exception.
 */
fun Path.createDirectories(vararg attributes: FileAttribute<*>): Path

/**
 * Ensures that all parent directories of this path exist, creating them if required.
 * If the parent directory already exists, this function does nothing.
 */
fun Path.createParentDirectories(vararg attributes: FileAttribute<*>): Path

Usage Examples:

import kotlin.io.path.*
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermissions

val projectDir = Paths.get("/home/user/new-project")

// Create directory structure
projectDir.createDirectories()

val srcDir = projectDir / "src"
val testDir = projectDir / "test"

srcDir.createDirectory()
testDir.createDirectory()

// Create files with parent directory creation
val mainFile = srcDir / "main.kt"
mainFile.createParentDirectories().createFile()

// Create with POSIX permissions (Unix/Linux)
val permissions = PosixFilePermissions.fromString("rwxr-xr-x")
val executableScript = projectDir / "run.sh"
executableScript.createFile(PosixFilePermissions.asFileAttribute(permissions))

File Operations

Copy, move, and delete files with various options and error handling.

/**
 * Copies a file or directory located by this path to the given target path.
 * If the target path already exists, this function will fail unless overwrite argument is set to true.
 */
fun Path.copyTo(target: Path, overwrite: Boolean = false): Path

/**
 * Copies a file or directory located by this path to the given target path with specified options.
 */
fun Path.copyTo(target: Path, vararg options: CopyOption): Path

/**
 * Moves or renames the file located by this path to the target path.
 */
fun Path.moveTo(target: Path, overwrite: Boolean = false): Path

/**
 * Moves or renames the file located by this path to the target path with specified options.
 */
fun Path.moveTo(target: Path, vararg options: CopyOption): Path

/**
 * Deletes the existing file or empty directory specified by this path.
 */
fun Path.deleteExisting()

/**
 * Deletes the file or empty directory specified by this path if it exists.
 * @return true if the existing file was successfully deleted, false if the file does not exist.
 */
fun Path.deleteIfExists(): Boolean

Usage Examples:

import kotlin.io.path.*
import java.nio.file.Paths
import java.nio.file.StandardCopyOption

val sourceFile = Paths.get("/home/user/document.txt")
val backupFile = Paths.get("/home/user/backup/document.txt")

// Ensure backup directory exists
backupFile.createParentDirectories()

// Copy file with overwrite
sourceFile.copyTo(backupFile, overwrite = true)

// Copy with specific options
sourceFile.copyTo(
    backupFile,
    StandardCopyOption.REPLACE_EXISTING,
    StandardCopyOption.COPY_ATTRIBUTES
)

// Move file
val archiveFile = Paths.get("/home/user/archive/old-document.txt")
archiveFile.createParentDirectories()
sourceFile.moveTo(archiveFile, overwrite = true)

// Safe deletion
val tempFile = Paths.get("/tmp/temp-file.txt")
if (tempFile.deleteIfExists()) {
    println("Temp file deleted")
} else {
    println("Temp file didn't exist")
}

Directory Listing

List and iterate through directory contents with glob pattern support.

/**
 * Returns a list of the entries in this directory optionally filtered by matching against the specified glob pattern.
 */
fun Path.listDirectoryEntries(glob: String = "*"): List<Path>

/**
 * Calls the block callback with a sequence of all entries in this directory
 * optionally filtered by matching against the specified glob pattern.
 */
fun <T> Path.useDirectoryEntries(glob: String = "*", block: (Sequence<Path>) -> T): T

/**
 * Performs the given action on each entry in this directory optionally filtered by matching against the specified glob pattern.
 */
fun Path.forEachDirectoryEntry(glob: String = "*", action: (Path) -> Unit)

Usage Examples:

import kotlin.io.path.*
import java.nio.file.Paths

val projectDir = Paths.get("/home/user/project")

// List all entries
val allEntries = projectDir.listDirectoryEntries()
println("All entries: ${allEntries.size}")

// List specific file types
val kotlinFiles = projectDir.listDirectoryEntries("*.kt")
kotlinFiles.forEach { file ->
    println("Kotlin file: ${file.name}")
}

// Use with sequence for memory efficiency
projectDir.useDirectoryEntries("*.{java,kt}") { entries ->
    entries.filter { it.isRegularFile() }
        .map { it.name }
        .toList()
}

// Perform action on each entry
projectDir.forEachDirectoryEntry("*.txt") { file ->
    println("Text file: ${file.name} (${file.fileSize()} bytes)")
}

File Size and Store Information

Get file size and file store information.

/**
 * Returns the size of a regular file as a Long value of bytes or throws an exception if the file doesn't exist.
 */
fun Path.fileSize(): Long

/**
 * Returns the FileStore representing the file store where a file is located.
 */
fun Path.fileStore(): FileStore

Usage Examples:

import kotlin.io.path.*
import java.nio.file.Paths

val largeFile = Paths.get("/home/user/video.mp4")

if (largeFile.exists()) {
    val sizeInBytes = largeFile.fileSize()
    val sizeInMB = sizeInBytes / (1024 * 1024)
    println("File size: $sizeInMB MB")
    
    val fileStore = largeFile.fileStore()
    println("File store: ${fileStore.name()}")
    println("Total space: ${fileStore.totalSpace / (1024 * 1024 * 1024)} GB")
    println("Available space: ${fileStore.usableSpace / (1024 * 1024 * 1024)} GB")
}

File Attributes

Read and write file attributes with comprehensive type support.

/**
 * Reads the value of a file attribute.
 * The attribute name is specified optionally prefixed with the attribute view name: [view_name:]attribute_name
 */
fun Path.getAttribute(attribute: String, vararg options: LinkOption): Any?

/**
 * Sets the value of a file attribute.
 */
fun Path.setAttribute(attribute: String, value: Any?, vararg options: LinkOption): Path

/**
 * Returns a file attributes view of a given type or null if the requested attribute view type is not available.
 */
inline fun <reified V : FileAttributeView> Path.fileAttributesViewOrNull(vararg options: LinkOption): V?

/**
 * Returns a file attributes view of a given type or throws an UnsupportedOperationException.
 */
inline fun <reified V : FileAttributeView> Path.fileAttributesView(vararg options: LinkOption): V

/**
 * Reads a file's attributes of the specified type in bulk.
 */
inline fun <reified A : BasicFileAttributes> Path.readAttributes(vararg options: LinkOption): A

/**
 * Reads the specified list of attributes of a file in bulk.
 */
fun Path.readAttributes(attributes: String, vararg options: LinkOption): Map<String, Any?>

Usage Examples:

import kotlin.io.path.*
import java.nio.file.Paths
import java.nio.file.attribute.*

val file = Paths.get("/home/user/important.txt")

// Read basic attributes
val attrs = file.readAttributes<BasicFileAttributes>()
println("Created: ${attrs.creationTime()}")
println("Modified: ${attrs.lastModifiedTime()}")
println("Size: ${attrs.size()}")

// Read specific attributes
val creationTime = file.getAttribute("creationTime") as FileTime
println("Creation time: $creationTime")

// Read multiple attributes at once
val attributeMap = file.readAttributes("size,lastModifiedTime,isDirectory")
attributeMap.forEach { (name, value) ->
    println("$name: $value")
}

// Work with POSIX attributes (Unix/Linux)
if (file.fileAttributesViewOrNull<PosixFileAttributeView>() != null) {
    val posixAttrs = file.readAttributes<PosixFileAttributes>()
    println("Owner: ${posixAttrs.owner()}")
    println("Group: ${posixAttrs.group()}")
    println("Permissions: ${PosixFilePermissions.toString(posixAttrs.permissions())}")
}

Time Operations

Get and set file timestamps with proper FileTime handling.

/**
 * Returns the last modified time of the file located by this path.
 */
fun Path.getLastModifiedTime(vararg options: LinkOption): FileTime

/**
 * Sets the last modified time attribute for the file located by this path.
 */
fun Path.setLastModifiedTime(value: FileTime): Path

Ownership and Permissions

Manage file ownership and POSIX permissions where supported.

/**
 * Returns the owner of a file.
 */
fun Path.getOwner(vararg options: LinkOption): UserPrincipal?

/**
 * Sets the file owner to the specified value.
 */
fun Path.setOwner(value: UserPrincipal): Path

/**
 * Returns the POSIX file permissions of the file located by this path.
 */
fun Path.getPosixFilePermissions(vararg options: LinkOption): Set<PosixFilePermission>

/**
 * Sets the POSIX file permissions for the file located by this path.
 */
fun Path.setPosixFilePermissions(value: Set<PosixFilePermission>): Path

Usage Examples:

import kotlin.io.path.*
import java.nio.file.Paths
import java.nio.file.attribute.*
import java.time.Instant

val file = Paths.get("/home/user/script.sh")

// Modify timestamp
val newTime = FileTime.from(Instant.now())
file.setLastModifiedTime(newTime)

// Change permissions (Unix/Linux)
val permissions = setOf(
    PosixFilePermission.OWNER_READ,
    PosixFilePermission.OWNER_WRITE,
    PosixFilePermission.OWNER_EXECUTE,
    PosixFilePermission.GROUP_READ,
    PosixFilePermission.GROUP_EXECUTE
)
file.setPosixFilePermissions(permissions)

// Change ownership (requires appropriate privileges)
val fileSystem = file.fileSystem
val userPrincipalLookupService = fileSystem.userPrincipalLookupService
val newOwner = userPrincipalLookupService.lookupPrincipalByName("newuser")
file.setOwner(newOwner)

Link Operations

Create and manage hard links and symbolic links.

/**
 * Creates a new link (directory entry) located by this path for the existing file target.
 */
fun Path.createLinkPointingTo(target: Path): Path

/**
 * Creates a new symbolic link located by this path to the given target.
 */
fun Path.createSymbolicLinkPointingTo(target: Path, vararg attributes: FileAttribute<*>): Path

/**
 * Reads the target of a symbolic link located by this path.
 */
fun Path.readSymbolicLink(): Path

Usage Examples:

import kotlin.io.path.*
import java.nio.file.Paths

val originalFile = Paths.get("/home/user/original.txt")
val hardLink = Paths.get("/home/user/hardlink.txt")
val symbolicLink = Paths.get("/home/user/symlink.txt")

// Create hard link
hardLink.createLinkPointingTo(originalFile)

// Create symbolic link
symbolicLink.createSymbolicLinkPointingTo(originalFile)

// Read symbolic link target
if (symbolicLink.isSymbolicLink()) {
    val target = symbolicLink.readSymbolicLink()
    println("Symbolic link points to: $target")
}

Temporary File and Directory Creation

Create temporary files and directories in system or custom temporary locations.

/**
 * Creates an empty file in the default temp directory, using
 * the given prefix and suffix to generate its name.
 */
fun createTempFile(prefix: String? = null, suffix: String? = null, vararg attributes: FileAttribute<*>): Path

/**
 * Creates an empty file in the specified directory, using
 * the given prefix and suffix to generate its name.
 */
fun createTempFile(directory: Path?, prefix: String? = null, suffix: String? = null, vararg attributes: FileAttribute<*>): Path

/**
 * Creates a new directory in the default temp directory, using the given prefix to generate its name.
 */
fun createTempDirectory(prefix: String? = null, vararg attributes: FileAttribute<*>): Path

/**
 * Creates a new directory in the specified directory, using the given prefix to generate its name.
 */
fun createTempDirectory(directory: Path?, prefix: String? = null, vararg attributes: FileAttribute<*>): Path

Usage Examples:

import kotlin.io.path.*
import java.nio.file.Paths

// Create temporary file in system temp directory
val tempFile = createTempFile("myapp-", ".tmp")
println("Created temp file: $tempFile")

// Create temporary file with custom location
val customTempDir = Paths.get("/tmp/myapp")
customTempDir.createDirectories()
val customTempFile = createTempFile(customTempDir, "data-", ".json")
println("Created custom temp file: $customTempFile")

// Create temporary directory
val tempDir = createTempDirectory("work-")
println("Created temp directory: $tempDir")

// Create temporary directory with custom parent
val workDir = Paths.get("/var/tmp")
val customTempDir2 = createTempDirectory(workDir, "processing-")
println("Created custom temp directory: $customTempDir2")

// Clean up (temp files are automatically cleaned by OS, but explicit cleanup is good practice)
tempFile.deleteIfExists()
customTempFile.deleteIfExists()
tempDir.deleteExisting()
customTempDir2.deleteExisting()

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-stdlib-jdk7

docs

file-io.md

file-system.md

index.md

path-operations.md

recursive-operations.md

tree-traversal.md

tile.json