or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

file-io.mdfile-system.mdindex.mdpath-operations.mdrecursive-operations.mdtree-traversal.md

file-system.mddocs/

0

# File System Operations

1

2

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

3

4

## Capabilities

5

6

### Existence and Type Checking

7

8

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

9

10

```kotlin { .api }

11

/**

12

* Checks if the file located by this path exists.

13

* @return true if the file definitely exists, false otherwise

14

*/

15

fun Path.exists(vararg options: LinkOption): Boolean

16

17

/**

18

* Checks if the file located by this path does not exist.

19

* @return true if the file definitely does not exist, false otherwise

20

*/

21

fun Path.notExists(vararg options: LinkOption): Boolean

22

23

/**

24

* Checks if the file located by this path is a regular file.

25

*/

26

fun Path.isRegularFile(vararg options: LinkOption): Boolean

27

28

/**

29

* Checks if the file located by this path is a directory.

30

*/

31

fun Path.isDirectory(vararg options: LinkOption): Boolean

32

33

/**

34

* Checks if the file located by this path exists and is a symbolic link.

35

*/

36

fun Path.isSymbolicLink(): Boolean

37

```

38

39

**Usage Examples:**

40

41

```kotlin

42

import kotlin.io.path.*

43

import java.nio.file.LinkOption

44

import java.nio.file.Paths

45

46

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

47

48

if (path.exists()) {

49

when {

50

path.isRegularFile() -> println("It's a regular file")

51

path.isDirectory() -> println("It's a directory")

52

path.isSymbolicLink() -> println("It's a symbolic link")

53

}

54

} else {

55

println("File does not exist")

56

}

57

58

// Check without following symbolic links

59

val link = Paths.get("/home/user/link-to-file")

60

val isLinkWithoutFollowing = link.isSymbolicLink()

61

val existsWithoutFollowing = link.exists(LinkOption.NOFOLLOW_LINKS)

62

```

63

64

### Permission and Property Checking

65

66

Check file permissions and properties with system-specific handling.

67

68

```kotlin { .api }

69

/**

70

* Checks if the file located by this path exists and is executable.

71

*/

72

fun Path.isExecutable(): Boolean

73

74

/**

75

* Checks if the file located by this path is considered hidden.

76

* This check is dependent on the current filesystem.

77

*/

78

fun Path.isHidden(): Boolean

79

80

/**

81

* Checks if the file located by this path exists and is readable.

82

*/

83

fun Path.isReadable(): Boolean

84

85

/**

86

* Checks if the file located by this path exists and is writable.

87

*/

88

fun Path.isWritable(): Boolean

89

90

/**

91

* Checks if the file located by this path points to the same file or directory as other.

92

*/

93

fun Path.isSameFileAs(other: Path): Boolean

94

```

95

96

**Usage Examples:**

97

98

```kotlin

99

import kotlin.io.path.*

100

import java.nio.file.Paths

101

102

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

103

104

// Check permissions

105

val permissions = listOf(

106

"readable" to scriptFile.isReadable(),

107

"writable" to scriptFile.isWritable(),

108

"executable" to scriptFile.isExecutable(),

109

"hidden" to scriptFile.isHidden()

110

)

111

112

permissions.forEach { (perm, hasIt) ->

113

println("$perm: $hasIt")

114

}

115

116

// Check if two paths point to the same file

117

val originalFile = Paths.get("/home/user/original.txt")

118

val linkFile = Paths.get("/home/user/link-to-original.txt")

119

if (originalFile.isSameFileAs(linkFile)) {

120

println("Both paths point to the same file")

121

}

122

```

123

124

### File and Directory Creation

125

126

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

127

128

```kotlin { .api }

129

/**

130

* Creates a new and empty file specified by this path, failing if the file already exists.

131

*/

132

fun Path.createFile(vararg attributes: FileAttribute<*>): Path

133

134

/**

135

* Creates a new directory or throws an exception if there is already a file or directory located by this path.

136

* Note that the parent directory where this directory is going to be created must already exist.

137

*/

138

fun Path.createDirectory(vararg attributes: FileAttribute<*>): Path

139

140

/**

141

* Creates a directory ensuring that all nonexistent parent directories exist by creating them first.

142

* If the directory already exists, this function does not throw an exception.

143

*/

144

fun Path.createDirectories(vararg attributes: FileAttribute<*>): Path

145

146

/**

147

* Ensures that all parent directories of this path exist, creating them if required.

148

* If the parent directory already exists, this function does nothing.

149

*/

150

fun Path.createParentDirectories(vararg attributes: FileAttribute<*>): Path

151

```

152

153

**Usage Examples:**

154

155

```kotlin

156

import kotlin.io.path.*

157

import java.nio.file.Paths

158

import java.nio.file.attribute.PosixFilePermissions

159

160

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

161

162

// Create directory structure

163

projectDir.createDirectories()

164

165

val srcDir = projectDir / "src"

166

val testDir = projectDir / "test"

167

168

srcDir.createDirectory()

169

testDir.createDirectory()

170

171

// Create files with parent directory creation

172

val mainFile = srcDir / "main.kt"

173

mainFile.createParentDirectories().createFile()

174

175

// Create with POSIX permissions (Unix/Linux)

176

val permissions = PosixFilePermissions.fromString("rwxr-xr-x")

177

val executableScript = projectDir / "run.sh"

178

executableScript.createFile(PosixFilePermissions.asFileAttribute(permissions))

179

```

180

181

### File Operations

182

183

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

184

185

```kotlin { .api }

186

/**

187

* Copies a file or directory located by this path to the given target path.

188

* If the target path already exists, this function will fail unless overwrite argument is set to true.

189

*/

190

fun Path.copyTo(target: Path, overwrite: Boolean = false): Path

191

192

/**

193

* Copies a file or directory located by this path to the given target path with specified options.

194

*/

195

fun Path.copyTo(target: Path, vararg options: CopyOption): Path

196

197

/**

198

* Moves or renames the file located by this path to the target path.

199

*/

200

fun Path.moveTo(target: Path, overwrite: Boolean = false): Path

201

202

/**

203

* Moves or renames the file located by this path to the target path with specified options.

204

*/

205

fun Path.moveTo(target: Path, vararg options: CopyOption): Path

206

207

/**

208

* Deletes the existing file or empty directory specified by this path.

209

*/

210

fun Path.deleteExisting()

211

212

/**

213

* Deletes the file or empty directory specified by this path if it exists.

214

* @return true if the existing file was successfully deleted, false if the file does not exist.

215

*/

216

fun Path.deleteIfExists(): Boolean

217

```

218

219

**Usage Examples:**

220

221

```kotlin

222

import kotlin.io.path.*

223

import java.nio.file.Paths

224

import java.nio.file.StandardCopyOption

225

226

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

227

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

228

229

// Ensure backup directory exists

230

backupFile.createParentDirectories()

231

232

// Copy file with overwrite

233

sourceFile.copyTo(backupFile, overwrite = true)

234

235

// Copy with specific options

236

sourceFile.copyTo(

237

backupFile,

238

StandardCopyOption.REPLACE_EXISTING,

239

StandardCopyOption.COPY_ATTRIBUTES

240

)

241

242

// Move file

243

val archiveFile = Paths.get("/home/user/archive/old-document.txt")

244

archiveFile.createParentDirectories()

245

sourceFile.moveTo(archiveFile, overwrite = true)

246

247

// Safe deletion

248

val tempFile = Paths.get("/tmp/temp-file.txt")

249

if (tempFile.deleteIfExists()) {

250

println("Temp file deleted")

251

} else {

252

println("Temp file didn't exist")

253

}

254

```

255

256

### Directory Listing

257

258

List and iterate through directory contents with glob pattern support.

259

260

```kotlin { .api }

261

/**

262

* Returns a list of the entries in this directory optionally filtered by matching against the specified glob pattern.

263

*/

264

fun Path.listDirectoryEntries(glob: String = "*"): List<Path>

265

266

/**

267

* Calls the block callback with a sequence of all entries in this directory

268

* optionally filtered by matching against the specified glob pattern.

269

*/

270

fun <T> Path.useDirectoryEntries(glob: String = "*", block: (Sequence<Path>) -> T): T

271

272

/**

273

* Performs the given action on each entry in this directory optionally filtered by matching against the specified glob pattern.

274

*/

275

fun Path.forEachDirectoryEntry(glob: String = "*", action: (Path) -> Unit)

276

```

277

278

**Usage Examples:**

279

280

```kotlin

281

import kotlin.io.path.*

282

import java.nio.file.Paths

283

284

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

285

286

// List all entries

287

val allEntries = projectDir.listDirectoryEntries()

288

println("All entries: ${allEntries.size}")

289

290

// List specific file types

291

val kotlinFiles = projectDir.listDirectoryEntries("*.kt")

292

kotlinFiles.forEach { file ->

293

println("Kotlin file: ${file.name}")

294

}

295

296

// Use with sequence for memory efficiency

297

projectDir.useDirectoryEntries("*.{java,kt}") { entries ->

298

entries.filter { it.isRegularFile() }

299

.map { it.name }

300

.toList()

301

}

302

303

// Perform action on each entry

304

projectDir.forEachDirectoryEntry("*.txt") { file ->

305

println("Text file: ${file.name} (${file.fileSize()} bytes)")

306

}

307

```

308

309

### File Size and Store Information

310

311

Get file size and file store information.

312

313

```kotlin { .api }

314

/**

315

* Returns the size of a regular file as a Long value of bytes or throws an exception if the file doesn't exist.

316

*/

317

fun Path.fileSize(): Long

318

319

/**

320

* Returns the FileStore representing the file store where a file is located.

321

*/

322

fun Path.fileStore(): FileStore

323

```

324

325

**Usage Examples:**

326

327

```kotlin

328

import kotlin.io.path.*

329

import java.nio.file.Paths

330

331

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

332

333

if (largeFile.exists()) {

334

val sizeInBytes = largeFile.fileSize()

335

val sizeInMB = sizeInBytes / (1024 * 1024)

336

println("File size: $sizeInMB MB")

337

338

val fileStore = largeFile.fileStore()

339

println("File store: ${fileStore.name()}")

340

println("Total space: ${fileStore.totalSpace / (1024 * 1024 * 1024)} GB")

341

println("Available space: ${fileStore.usableSpace / (1024 * 1024 * 1024)} GB")

342

}

343

```

344

345

### File Attributes

346

347

Read and write file attributes with comprehensive type support.

348

349

```kotlin { .api }

350

/**

351

* Reads the value of a file attribute.

352

* The attribute name is specified optionally prefixed with the attribute view name: [view_name:]attribute_name

353

*/

354

fun Path.getAttribute(attribute: String, vararg options: LinkOption): Any?

355

356

/**

357

* Sets the value of a file attribute.

358

*/

359

fun Path.setAttribute(attribute: String, value: Any?, vararg options: LinkOption): Path

360

361

/**

362

* Returns a file attributes view of a given type or null if the requested attribute view type is not available.

363

*/

364

inline fun <reified V : FileAttributeView> Path.fileAttributesViewOrNull(vararg options: LinkOption): V?

365

366

/**

367

* Returns a file attributes view of a given type or throws an UnsupportedOperationException.

368

*/

369

inline fun <reified V : FileAttributeView> Path.fileAttributesView(vararg options: LinkOption): V

370

371

/**

372

* Reads a file's attributes of the specified type in bulk.

373

*/

374

inline fun <reified A : BasicFileAttributes> Path.readAttributes(vararg options: LinkOption): A

375

376

/**

377

* Reads the specified list of attributes of a file in bulk.

378

*/

379

fun Path.readAttributes(attributes: String, vararg options: LinkOption): Map<String, Any?>

380

```

381

382

**Usage Examples:**

383

384

```kotlin

385

import kotlin.io.path.*

386

import java.nio.file.Paths

387

import java.nio.file.attribute.*

388

389

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

390

391

// Read basic attributes

392

val attrs = file.readAttributes<BasicFileAttributes>()

393

println("Created: ${attrs.creationTime()}")

394

println("Modified: ${attrs.lastModifiedTime()}")

395

println("Size: ${attrs.size()}")

396

397

// Read specific attributes

398

val creationTime = file.getAttribute("creationTime") as FileTime

399

println("Creation time: $creationTime")

400

401

// Read multiple attributes at once

402

val attributeMap = file.readAttributes("size,lastModifiedTime,isDirectory")

403

attributeMap.forEach { (name, value) ->

404

println("$name: $value")

405

}

406

407

// Work with POSIX attributes (Unix/Linux)

408

if (file.fileAttributesViewOrNull<PosixFileAttributeView>() != null) {

409

val posixAttrs = file.readAttributes<PosixFileAttributes>()

410

println("Owner: ${posixAttrs.owner()}")

411

println("Group: ${posixAttrs.group()}")

412

println("Permissions: ${PosixFilePermissions.toString(posixAttrs.permissions())}")

413

}

414

```

415

416

### Time Operations

417

418

Get and set file timestamps with proper FileTime handling.

419

420

```kotlin { .api }

421

/**

422

* Returns the last modified time of the file located by this path.

423

*/

424

fun Path.getLastModifiedTime(vararg options: LinkOption): FileTime

425

426

/**

427

* Sets the last modified time attribute for the file located by this path.

428

*/

429

fun Path.setLastModifiedTime(value: FileTime): Path

430

```

431

432

### Ownership and Permissions

433

434

Manage file ownership and POSIX permissions where supported.

435

436

```kotlin { .api }

437

/**

438

* Returns the owner of a file.

439

*/

440

fun Path.getOwner(vararg options: LinkOption): UserPrincipal?

441

442

/**

443

* Sets the file owner to the specified value.

444

*/

445

fun Path.setOwner(value: UserPrincipal): Path

446

447

/**

448

* Returns the POSIX file permissions of the file located by this path.

449

*/

450

fun Path.getPosixFilePermissions(vararg options: LinkOption): Set<PosixFilePermission>

451

452

/**

453

* Sets the POSIX file permissions for the file located by this path.

454

*/

455

fun Path.setPosixFilePermissions(value: Set<PosixFilePermission>): Path

456

```

457

458

**Usage Examples:**

459

460

```kotlin

461

import kotlin.io.path.*

462

import java.nio.file.Paths

463

import java.nio.file.attribute.*

464

import java.time.Instant

465

466

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

467

468

// Modify timestamp

469

val newTime = FileTime.from(Instant.now())

470

file.setLastModifiedTime(newTime)

471

472

// Change permissions (Unix/Linux)

473

val permissions = setOf(

474

PosixFilePermission.OWNER_READ,

475

PosixFilePermission.OWNER_WRITE,

476

PosixFilePermission.OWNER_EXECUTE,

477

PosixFilePermission.GROUP_READ,

478

PosixFilePermission.GROUP_EXECUTE

479

)

480

file.setPosixFilePermissions(permissions)

481

482

// Change ownership (requires appropriate privileges)

483

val fileSystem = file.fileSystem

484

val userPrincipalLookupService = fileSystem.userPrincipalLookupService

485

val newOwner = userPrincipalLookupService.lookupPrincipalByName("newuser")

486

file.setOwner(newOwner)

487

```

488

489

### Link Operations

490

491

Create and manage hard links and symbolic links.

492

493

```kotlin { .api }

494

/**

495

* Creates a new link (directory entry) located by this path for the existing file target.

496

*/

497

fun Path.createLinkPointingTo(target: Path): Path

498

499

/**

500

* Creates a new symbolic link located by this path to the given target.

501

*/

502

fun Path.createSymbolicLinkPointingTo(target: Path, vararg attributes: FileAttribute<*>): Path

503

504

/**

505

* Reads the target of a symbolic link located by this path.

506

*/

507

fun Path.readSymbolicLink(): Path

508

```

509

510

**Usage Examples:**

511

512

```kotlin

513

import kotlin.io.path.*

514

import java.nio.file.Paths

515

516

val originalFile = Paths.get("/home/user/original.txt")

517

val hardLink = Paths.get("/home/user/hardlink.txt")

518

val symbolicLink = Paths.get("/home/user/symlink.txt")

519

520

// Create hard link

521

hardLink.createLinkPointingTo(originalFile)

522

523

// Create symbolic link

524

symbolicLink.createSymbolicLinkPointingTo(originalFile)

525

526

// Read symbolic link target

527

if (symbolicLink.isSymbolicLink()) {

528

val target = symbolicLink.readSymbolicLink()

529

println("Symbolic link points to: $target")

530

}

531

```

532

533

### Temporary File and Directory Creation

534

535

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

536

537

```kotlin { .api }

538

/**

539

* Creates an empty file in the default temp directory, using

540

* the given prefix and suffix to generate its name.

541

*/

542

fun createTempFile(prefix: String? = null, suffix: String? = null, vararg attributes: FileAttribute<*>): Path

543

544

/**

545

* Creates an empty file in the specified directory, using

546

* the given prefix and suffix to generate its name.

547

*/

548

fun createTempFile(directory: Path?, prefix: String? = null, suffix: String? = null, vararg attributes: FileAttribute<*>): Path

549

550

/**

551

* Creates a new directory in the default temp directory, using the given prefix to generate its name.

552

*/

553

fun createTempDirectory(prefix: String? = null, vararg attributes: FileAttribute<*>): Path

554

555

/**

556

* Creates a new directory in the specified directory, using the given prefix to generate its name.

557

*/

558

fun createTempDirectory(directory: Path?, prefix: String? = null, vararg attributes: FileAttribute<*>): Path

559

```

560

561

**Usage Examples:**

562

563

```kotlin

564

import kotlin.io.path.*

565

import java.nio.file.Paths

566

567

// Create temporary file in system temp directory

568

val tempFile = createTempFile("myapp-", ".tmp")

569

println("Created temp file: $tempFile")

570

571

// Create temporary file with custom location

572

val customTempDir = Paths.get("/tmp/myapp")

573

customTempDir.createDirectories()

574

val customTempFile = createTempFile(customTempDir, "data-", ".json")

575

println("Created custom temp file: $customTempFile")

576

577

// Create temporary directory

578

val tempDir = createTempDirectory("work-")

579

println("Created temp directory: $tempDir")

580

581

// Create temporary directory with custom parent

582

val workDir = Paths.get("/var/tmp")

583

val customTempDir2 = createTempDirectory(workDir, "processing-")

584

println("Created custom temp directory: $customTempDir2")

585

586

// Clean up (temp files are automatically cleaned by OS, but explicit cleanup is good practice)

587

tempFile.deleteIfExists()

588

customTempFile.deleteIfExists()

589

tempDir.deleteExisting()

590

customTempDir2.deleteExisting()

591

```