Last active
May 7, 2016 10:44
-
-
Save gitbricho/e15fbfa2da5513788f4a to your computer and use it in GitHub Desktop.
swift 2.1 ファイル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
//## iOS:ファイルシステム ##### | |
//標準ディレクトリ ( Documents/, Library/, tmp/ ... ) | |
//## OS X:ファイルシステム ##### | |
//ローカルドメイン ( Applications/Utilities, Developer/, Library/ ) | |
//ユーザードメイン ( Users/user1, ... ) | |
//ファイルまたはディレクトリのパス | |
// Path ベースの URL : file://localhost/Users/user1/doc/MyFile.txt | |
// File 参照 URL : file:///Users/user1/doc/MyFile.txt | |
// 文字列ベースの パス : /Users/user1/doc/MyFile.txt | |
//ホームディレクトリの表示 | |
print("ホームディレクトリ:\(NSHomeDirectory())") | |
//## ファイルマネージャー・オブジェクトの作成 | |
let lファイルマネージャ = NSFileManager.defaultManager() | |
let lカレントパス:String = lファイルマネージャ.currentDirectoryPath | |
print("カレントパス:\(lカレントパス)") | |
var dirArray:[String] = lカレントパス.componentsSeparatedByString("/") //debug | |
//## iOS のドキュメントディレクトリ (Documents/) の取得 | |
let lドキュメントパス配列:[String] = NSSearchPathForDirectoriesInDomains( | |
.DocumentDirectory, .UserDomainMask, true) | |
let lドキュメントパス:String = lドキュメントパス配列[0] | |
print("ドキュメントパス:\(lドキュメントパス)") | |
dirArray = lドキュメントパス.componentsSeparatedByString("/") //debug | |
//## iOS の一時ディレクトリ (tmp/) の取得 | |
let l一時Dir = NSTemporaryDirectory() as String | |
dirArray = l一時Dir.componentsSeparatedByString("/") //debug | |
//## カレントディレクトリの変更 --> Documents/ | |
if lファイルマネージャ.changeCurrentDirectoryPath(lドキュメントパス) { | |
print("カレントディレクトリの変更に成功") | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//## 新規ディレクトリの作成 | |
// NSFileManager を使って /Documents に新規ディレクトリ images を作成する | |
do { | |
let lドキュメントURL:NSURL = try lファイルマネージャ.URLForDirectory( | |
.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) | |
let lイメージDirURL:NSURL = lドキュメントURL.URLByAppendingPathComponent("images") | |
try lファイルマネージャ.createDirectoryAtURL( | |
lイメージDirURL, withIntermediateDirectories: false, attributes: nil) | |
} catch let error as NSError { | |
if error.code == 516 { | |
print("そのディレクトリは既に存在します") | |
} else { | |
print(error) | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//## 指定ディレクトリのファイル一覧の取得 | |
// 関数を作成: (String) -> ([String]) | |
func Fファイル一覧(一覧取得パス:String) -> [String]{ | |
print("ファイル一覧取得パス:\(一覧取得パス)") | |
let fs: NSFileManager = NSFileManager.defaultManager() | |
var isDir: ObjCBool = false | |
if (fs.fileExistsAtPath(一覧取得パス, isDirectory: &isDir)) { | |
do { | |
return try fs.contentsOfDirectoryAtPath(一覧取得パス) | |
} catch let error as NSError { | |
print(error.localizedDescription) | |
return [] | |
} | |
} | |
return [] | |
} | |
print("##### ファイル一覧 #####") | |
let lファイル一覧:[String] = Fファイル一覧(lドキュメントパス) | |
for ファイル名 in lファイル一覧 { | |
print(">> \(ファイル名)") | |
} | |
/* 結果: | |
>> images | |
>> MyFile.txt | |
>> MyFile1.txt | |
>> MyFileXX.txt | |
*/ | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//# 拡張 Extentios を使ってディレクトリ一覧を取得する | |
// Extensions は既存のクラス、ストラクチャ、列挙型、プロトコルに新規機能を追加する | |
// シンタックス: extension 型 {} | |
// 以下は NSURL クラスに3つの計算型プロパティを追加する | |
extension NSURL { | |
// この URLがディレクトリかどうか判定 | |
var isDirectory: Bool { | |
guard let path = path where fileURL else { | |
return false | |
} | |
var bool: ObjCBool = false | |
return NSFileManager().fileExistsAtPath(path, isDirectory: &bool) | |
? bool.boolValue : false | |
} | |
// この URLのサブディレクトリ配列を取得 | |
var subdirUrls: [NSURL] { | |
guard isDirectory else { | |
return [] | |
} | |
do { | |
return try NSFileManager.defaultManager() | |
.contentsOfDirectoryAtURL(self, includingPropertiesForKeys: nil, options: []) | |
.filter{ $0.isDirectory } | |
} catch let error as NSError { | |
print(error.localizedDescription) | |
return [] | |
} | |
} | |
// この URLのファイル一覧配列を取得 | |
var fileUrls: [NSURL] { | |
guard isDirectory else { | |
return [] | |
} | |
do { | |
return try NSFileManager.defaultManager() | |
.contentsOfDirectoryAtURL(self, includingPropertiesForKeys: nil, options: []) | |
.filter{ !$0.isDirectory } | |
} catch let error as NSError { | |
print(error.localizedDescription) | |
return [] | |
} | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 拡張した NSURL を使用して /Documents のサブディレクトリを取得 | |
let lドキュメントURL:NSURL = try lファイルマネージャ.URLForDirectory( | |
.DocumentDirectory, inDomain: .UserDomainMask, | |
appropriateForURL: nil, create: true) | |
let lサブディレクトリ一覧 = lドキュメントURL.subdirUrls | |
for サブディレクトリパス in lサブディレクトリ一覧 { | |
let lサブディレクトリ = サブディレクトリパス.path!.componentsSeparatedByString("/").last! | |
print("ドキュメントURLのサブディレクトリ:\(lサブディレクトリ)") | |
} | |
/* 結果: | |
ドキュメントURLのサブディレクトリ:images | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 拡張した NSURL を使用して /Documents のファイル一覧を取得 | |
let lファイル一覧Urls = lドキュメントURL.fileUrls | |
for ファイルパス in lファイル一覧Urls { | |
let lファイル = ファイルパス.path!.componentsSeparatedByString("/").last! | |
print("ドキュメントURLのファイル:\(lファイル)") | |
} | |
/* 結果: | |
ドキュメントURLのファイル:MyFile.txt | |
ドキュメントURLのファイル:MyFile1.txt | |
ドキュメントURLのファイル:MyFileXX.txt | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//## ファイルの削除 MyFile.txt, MyFile1.txt, MyFileXX.txt | |
do { | |
for ファイルパス in lファイル一覧Urls { | |
if let fPath = ファイルパス.path { | |
print("削除するファイル:\(fPath)") | |
try lファイルマネージャ.removeItemAtPath(fPath) | |
} | |
} | |
} catch let error as NSError { | |
print(error.localizedDescription) | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//## ファイル: 書き込み /Documents/MyFile.txt | |
if let lドキュメントDir : NSString = NSSearchPathForDirectoriesInDomains( | |
NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true ).first { | |
let l出力パス = lドキュメントDir.stringByAppendingPathComponent("MyFile.txt") | |
let dirs = l出力パス.componentsSeparatedByString("/") //デバッグ目的 | |
do { | |
try "出力文字列".writeToFile( l出力パス, atomically: false, encoding: NSUTF8StringEncoding ) | |
} catch let error as NSError { | |
print(error.localizedDescription) | |
} | |
} | |
//# 関数を作成して書く: (String, String) -> (String) | |
func Fファイルの書き込み(ファイルパス:String, 出力文字列:String) -> String { | |
do { | |
try 出力文字列.writeToFile(ファイルパス, atomically: false, encoding: NSUTF8StringEncoding ) | |
return "成功" | |
} catch let error as NSError { | |
return error.localizedDescription | |
} | |
} | |
// ==> /Documents/MyFile1.txt | |
Fファイルの書き込み("MyFile1.txt", 出力文字列: "ABCDE") | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//# 関数を作成してファイルに追加; (String, String) -> () | |
func Fファイルに追加(ファイルパス:String, 追加テキスト:String){ | |
let os: NSOutputStream = NSOutputStream(toFileAtPath: ファイルパス, append: true)! | |
os.open() | |
os.write(追加テキスト, maxLength: 追加テキスト.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) | |
os.close() | |
} | |
for text in ["行0001","行0002","行0003" ] { | |
Fファイルに追加("MyFileXX.txt", 追加テキスト: "\(text)\n") | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//## ファイルを読む <== /Documents/Myfile.txt | |
if let lドキュメントDir : NSString = NSSearchPathForDirectoriesInDomains( | |
NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true ).first { | |
let l入力パス = lドキュメントDir.stringByAppendingPathComponent("MyFile.txt") | |
do { | |
let l入力内容 = try NSString( contentsOfFile: l入力パス, encoding: NSUTF8StringEncoding ) | |
print(l入力内容) | |
} catch let error as NSError { | |
print(error.localizedDescription) | |
} | |
} | |
//#関数を作成して読む: (String) -> (Int, String) | |
func Fファイルの読み込み(ファイルパス:String) -> (Int, String) { | |
do { | |
let l入力内容 = try NSString( contentsOfFile: ファイルパス, encoding: NSUTF8StringEncoding ) | |
return (0, l入力内容 as String) | |
} catch let error as NSError { | |
return(error.code, error.localizedDescription) | |
} | |
} | |
// <== /Documents/MyFile2.txt | |
print("MyFile1.txt の読み込み: \(Fファイルの読み込み("MyFile1.txt"))") //MyFile1.txt の読み込み: (0, "ABCDE") | |
print("MyFileXX.txt の読み込み: \(Fファイルの読み込み("MyFileXX.txt"))") | |
// 結果: MyFileXX.txt の読み込み: (0, "行0001\n行0002\n行0003\n") | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//## ファイルやURLへの文字列の読み書き | |
//# URL への書き込み | |
let outputStr = "ABC" | |
let urlStr = NSHomeDirectory() + "/_test01.txt" | |
let url:NSURL = NSURL(fileURLWithPath: urlStr) | |
try outputStr.writeToURL(url,atomically: true, | |
encoding: NSUTF8StringEncoding) | |
//# 文字列を拡張して appendToFile()メソッドを追加 | |
extension String { | |
func appendToFile(path:String, encoding: NSStringEncoding) -> Void{ | |
let os: NSOutputStream = NSOutputStream(toFileAtPath: path, append: true)! | |
os.open() | |
os.write(self, maxLength: self.lengthOfBytesUsingEncoding(encoding)) | |
os.close() | |
} | |
} | |
"\nXYZ".appendToFile(urlStr, encoding: NSUTF8StringEncoding) | |
//# URL からの読み込み | |
var inputStr: String = try NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding) as String | |
print("inputStr:\(inputStr)") | |
/*結果: | |
inputStr:ABC | |
XYZ | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment