0
# Path Operations
1
2
Core path manipulation functionality providing string properties, resolution operations, relativization, and factory functions for robust file system navigation.
3
4
## Capabilities
5
6
### Path Properties
7
8
Access path components as strings with proper handling of edge cases.
9
10
```kotlin { .api }
11
/**
12
* Returns the name of the file or directory denoted by this path as a string,
13
* or an empty string if this path has zero path elements.
14
*/
15
val Path.name: String
16
17
/**
18
* Returns the name of this file or directory without an extension,
19
* or an empty string if this path has zero path elements.
20
*/
21
val Path.nameWithoutExtension: String
22
23
/**
24
* Returns the extension of this path (not including the dot),
25
* or an empty string if it doesn't have one.
26
*/
27
val Path.extension: String
28
29
/**
30
* Returns the string representation of this path using the default name separator.
31
* This property is a synonym to Path.toString() function.
32
*/
33
val Path.pathString: String
34
35
/**
36
* Returns the string representation of this path using the invariant separator '/'
37
* to separate names in the path.
38
*/
39
val Path.invariantSeparatorsPathString: String
40
41
/**
42
* @deprecated Use invariantSeparatorsPathString property instead.
43
* Returns the string representation of this path using the invariant separator '/'.
44
*/
45
@Deprecated("Use invariantSeparatorsPathString property instead.", ReplaceWith("invariantSeparatorsPathString"))
46
val Path.invariantSeparatorsPath: String
47
```
48
49
**Usage Examples:**
50
51
```kotlin
52
import kotlin.io.path.*
53
import java.nio.file.Paths
54
55
val path = Paths.get("/home/user/documents/report.pdf")
56
57
println(path.name) // "report.pdf"
58
println(path.nameWithoutExtension) // "report"
59
println(path.extension) // "pdf"
60
println(path.pathString) // "/home/user/documents/report.pdf"
61
println(path.invariantSeparatorsPathString) // "/home/user/documents/report.pdf" (Unix) or converts \ to / (Windows)
62
63
// Edge cases
64
val root = Paths.get("/")
65
println(root.name) // ""
66
println(root.extension) // ""
67
```
68
69
### Path Resolution
70
71
Convert between relative and absolute paths with proper resolution handling.
72
73
```kotlin { .api }
74
/**
75
* Converts this possibly relative path to an absolute path.
76
* If this path is already absolute, returns this path unchanged.
77
*/
78
fun Path.absolute(): Path
79
80
/**
81
* Converts this possibly relative path to an absolute path and returns its string representation.
82
* Basically, this method is a combination of calling absolute() and pathString.
83
* May throw an exception if the file system is inaccessible or getting the default directory path is prohibited.
84
*/
85
fun Path.absolutePathString(): String
86
```
87
88
**Usage Examples:**
89
90
```kotlin
91
import kotlin.io.path.*
92
import java.nio.file.Paths
93
94
val relativePath = Paths.get("../config/settings.xml")
95
val absolutePath = relativePath.absolute()
96
println("Absolute path: $absolutePath")
97
98
// Get absolute path as string in one call
99
val absoluteString = relativePath.absolutePathString()
100
println("Absolute string: $absoluteString")
101
```
102
103
### Path Relativization
104
105
Calculate relative paths between different locations with error handling for different roots.
106
107
```kotlin { .api }
108
/**
109
* Calculates the relative path for this path from a base path.
110
* Note that the base path is treated as a directory.
111
* @throws IllegalArgumentException if this and base paths have different roots.
112
*/
113
fun Path.relativeTo(base: Path): Path
114
115
/**
116
* Calculates the relative path for this path from a base path.
117
* @return the relative path from base to this, or this if this and base paths have different roots.
118
*/
119
fun Path.relativeToOrSelf(base: Path): Path
120
121
/**
122
* Calculates the relative path for this path from a base path.
123
* @return the relative path from base to this, or null if this and base paths have different roots.
124
*/
125
fun Path.relativeToOrNull(base: Path): Path?
126
```
127
128
**Usage Examples:**
129
130
```kotlin
131
import kotlin.io.path.*
132
import java.nio.file.Paths
133
134
val basePath = Paths.get("/home/user/projects")
135
val targetPath = Paths.get("/home/user/projects/myapp/src/main.kt")
136
137
// Calculate relative path
138
val relativePath = targetPath.relativeTo(basePath)
139
println(relativePath) // "myapp/src/main.kt"
140
141
// Safe variant that returns self if different roots
142
val safeRelative = targetPath.relativeToOrSelf(basePath)
143
println(safeRelative)
144
145
// Nullable variant
146
val nullableRelative = targetPath.relativeToOrNull(basePath)
147
println(nullableRelative ?: "Different roots")
148
```
149
150
### Path Division Operators
151
152
Convenient operators for path resolution and joining.
153
154
```kotlin { .api }
155
/**
156
* Resolves the given other path against this path.
157
* This operator is a shortcut for the Path.resolve function.
158
*/
159
operator fun Path.div(other: Path): Path
160
161
/**
162
* Resolves the given other path string against this path.
163
* This operator is a shortcut for the Path.resolve function.
164
*/
165
operator fun Path.div(other: String): Path
166
```
167
168
**Usage Examples:**
169
170
```kotlin
171
import kotlin.io.path.*
172
import java.nio.file.Paths
173
174
val baseDir = Paths.get("/home/user")
175
val configDir = baseDir / "config"
176
val configFile = configDir / "app.properties"
177
178
println(configFile) // "/home/user/config/app.properties"
179
180
// Combining with other paths
181
val logsPath = Paths.get("logs")
182
val fullLogsPath = baseDir / logsPath
183
println(fullLogsPath) // "/home/user/logs"
184
```
185
186
### Path Factory Functions
187
188
Create Path instances from strings and URIs with proper handling.
189
190
```kotlin { .api }
191
/**
192
* Converts the provided path string to a Path object of the default filesystem.
193
*/
194
fun Path(path: String): Path
195
196
/**
197
* Converts the name sequence specified with the base path string and a number of subpaths
198
* additional names to a Path object of the default filesystem.
199
*/
200
fun Path(base: String, vararg subpaths: String): Path
201
202
/**
203
* Converts this URI to a Path object.
204
*/
205
fun URI.toPath(): Path
206
```
207
208
**Usage Examples:**
209
210
```kotlin
211
import kotlin.io.path.*
212
import java.net.URI
213
214
// Create paths from strings
215
val simplePath = Path("/home/user/file.txt")
216
val composedPath = Path("/home", "user", "documents", "report.pdf")
217
218
println(simplePath) // "/home/user/file.txt"
219
println(composedPath) // "/home/user/documents/report.pdf"
220
221
// Create path from URI
222
val uri = URI("file:///home/user/file.txt")
223
val pathFromUri = uri.toPath()
224
println(pathFromUri) // "/home/user/file.txt"
225
```
226
227
### Temporary Files and Directories
228
229
Create temporary files and directories with optional prefixes, suffixes, and attributes.
230
231
```kotlin { .api }
232
/**
233
* Creates an empty file in the default temp directory, using
234
* the given prefix and suffix to generate its name.
235
*/
236
fun createTempFile(prefix: String? = null, suffix: String? = null, vararg attributes: FileAttribute<*>): Path
237
238
/**
239
* Creates an empty file in the specified directory, using
240
* the given prefix and suffix to generate its name.
241
*/
242
fun createTempFile(directory: Path?, prefix: String? = null, suffix: String? = null, vararg attributes: FileAttribute<*>): Path
243
244
/**
245
* Creates a new directory in the default temp directory, using the given prefix to generate its name.
246
*/
247
fun createTempDirectory(prefix: String? = null, vararg attributes: FileAttribute<*>): Path
248
249
/**
250
* Creates a new directory in the specified directory, using the given prefix to generate its name.
251
*/
252
fun createTempDirectory(directory: Path?, prefix: String? = null, vararg attributes: FileAttribute<*>): Path
253
```
254
255
**Usage Examples:**
256
257
```kotlin
258
import kotlin.io.path.*
259
260
// Create temporary files
261
val tempFile = createTempFile("myapp", ".tmp")
262
println("Created temp file: $tempFile")
263
264
val tempConfig = createTempFile(prefix = "config", suffix = ".properties")
265
println("Created temp config: $tempConfig")
266
267
// Create temporary directories
268
val tempDir = createTempDirectory("workspace")
269
println("Created temp directory: $tempDir")
270
271
// Create in specific directory
272
val workDir = Path("/var/tmp")
273
val projectTemp = createTempDirectory(workDir, "project")
274
println("Created project temp: $projectTemp")
275
```