/
File.swift
86 lines (71 loc) · 2.5 KB
/
File.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// File.swift
// SwiftFilePath
//
// Created by nori0620 on 2015/01/08.
// Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved.
//
public class File: Entity {
public var extention:NSString {
return path.pathExtension
}
public var dir:Dir {
return Dir( path.stringByDeletingLastPathComponent )
}
public func touch() -> Result<File,String> {
return self.exists
? self.updateModificationDate()
: self.createEmptyFile()
}
public func updateModificationDate(date: NSDate = NSDate() ) -> Result<File,String>{
var error: NSError?
let result = fileManager.setAttributes(
[NSFileModificationDate :date],
ofItemAtPath:path,
error:&error
)
return result
? Result(success: self)
: Result(failure: "Failed to modify file.< error:\(error?.localizedDescription) path:\(path) >");
}
private func createEmptyFile() -> Result<File,String>{
let result = fileManager.createFileAtPath(path,
contents:NSData(),
attributes:nil
)
return result
? Result(success: self)
: Result(failure: "Failed to create file:\(path)");
}
// MARK: - read/write String
public func readString() -> String? {
var readError:NSError?
let read = String(contentsOfFile: path,
encoding: NSUTF8StringEncoding,
error: &readError)
if let error = readError {
println("readError< \(error.localizedDescription) >")
}
return read
}
public func writeString(string:String) -> Result<File,String> {
var error: NSError?
let result = string.writeToFile(path,
atomically:true,
encoding: NSUTF8StringEncoding,
error: &error)
return result
? Result(success: self)
: Result(failure: "Failed to write file.< error:\(error?.localizedDescription) path:\(path) >");
}
// MARK: - read/write NSData
public func readData() -> NSData? {
return NSData(contentsOfFile: path)
}
public func writeData(data:NSData) -> Result<File,String> {
let result = data.writeToFile(path, atomically:true)
return result
? Result(success: self)
: Result(failure: "Failed to write file.< path:\(path) >");
}
}