LoginSignup
3
1

More than 5 years have passed since last update.

Swift3 で touch, mkdir, ls

Posted at

概要

Swift のファイル操作まわりを自分用にメモ

  • touch: ファイル作成
  • mkdir: ディレクトリ作成
  • ls: ディレクトリ配下のファイル名を取得

コード


let documentUrl =  FileManager.default.urls(
    for: .documentDirectory, in: .userDomainMask).first!

// "touch"

let touchPath = documentUrl.appendingPathComponent("file.txt")
let text = "(ここにテキストファイルの内容を書く)"
do {
    try text.write(
        to: touchPath,
        atomically: false,
        encoding: String.Encoding.utf8 )

} catch let error as NSError {
    print(error.localizedDescription);
}

// "mkdir"

let mkdirPath = documentUrl.appendingPathComponent("MyFolder")
do {
    try FileManager.default.createDirectory(
        atPath: mkdirPath.path,
        withIntermediateDirectories: false,
        attributes: nil)

} catch let error as NSError {
    print(error.localizedDescription);
}


// "ls"

do {
    let directoryContents =
        try FileManager.default.contentsOfDirectory(atPath: documentUrl.path)

    print(directoryContents)

} catch let error as NSError {
    print(error.localizedDescription)
}

注: mkdir, lsatPath.absoluteStringで取得される文字列("file:///...")だと「The file “...” doesn’t exist.」というエラーになります。.pathを使ってください。

参考リンク

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1