Title Image

Modified : 2023/10/08

パス名の操作

Kotlinでファイルやディレクトリのパス名を操作する方法を紹介します。
[Kotlin]に戻る

[記事の先頭]

カレントディレクトリを取得する。

 Paths.get("").toAbsolutePath()で、カレントパスを取得することができます。

サンプル

import java.nio.file.Paths

val currentDirPath = Paths.get("").toAbsolutePath()
println("Current Directory Path: $currentDirPath")
[記事の先頭]

カレントディレクトリのパスにファイル名を連結する。

 Paths.get(dirPath, fileName)で、ディレクトリのパス名とファイル名を連結することができます。

サンプル

import java.nio.file.Paths

val currentDirPath = Paths.get("").toAbsolutePath()
val textFilePath = Paths.get(currentDirPath.toString(), "test.txt")
println("Text File Path: $textFilePath")
[記事の先頭]

Pathsクラスで色々な情報を取得する。

 Pathsクラスには、色々な情報を取得するためのプロパティが用意されています。

サンプル

val filePath = Paths.get("/User/apricottail/data/test.txt")

println("File Path        : $filePath")
println("Root             : ${filePath.root}")
println("Parent Directory : ${filePath.parent}")
println("File Name        : ${filePath.fileName}")

println("Name Count : ${filePath.nameCount}")
for (index in 0..filePath.nameCount - 1) {
    println(" Name : ${filePath.getName(index)}")
}

サンプルの実行結果

File Path        : /Users/apricottail/data/test.txt
Root             : /
Parent Directory : /Users/apricottail/data
File Name        : test.txt
Name Count : 4
 Name : Users
 Name : apricottail
 Name : data
 Name : test.txt
[記事の先頭]

関連記事

[記事の先頭]
[Kotlin]に戻る