2014-11-14 5 views
6

다음 주에 내 대학의 짧은 프레젠테이션을 위해 신속한 파일 입출력 작업을 검색하고 있습니다. 나는 그것에 대해별로 알지 못했다.Apple Swift File IO 작업

여기에 내가있는 작업은 다음과 같습니다

let location = "/Users/test/test.txt" 
var str = "Hello, playground" 

//write 
str.writeToFile(location, atomically: false, encoding: NSUTF8StringEncoding, error: nil) 
//read 
let filecontent = String(contentsOfFile: location, encoding: NSUTF8StringEncoding, error: nil) 
//binary read 
let test = NSData(contentsOfFile: location) 
//if file exists 
NSFileManager().fileExistsAtPath(location) 
//find Files in the App Bundle with suffix test and prefix txt 
var path= NSBundle.mainBundle().pathForResource("test", ofType: "txt") 
//path for dynamic user names 
if let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] { 
let path = dirs[0].stringByAppendingPathComponent("file.txt") 
//printout: /Users/test/Documents/file.txt 

있는 내가 하나의 문자를 읽을 수 있습니다 거기에 운영 있습니까?
파일에 텍스트를 추가 할 수 있습니까?
문자열 만 쓰거나 읽을 수 있습니까?
알아 두어야 할 다른 파일 작업이 있습니까?

+1

귀하의 질문은 약간 넓지 만 NSInputStream과 NSOutputStream을 살펴보아야합니다. –

+1

... NSFileHandle도 있습니다 ... –

답변

2

하나의 문자를 읽을 수있는 작업이 있습니까?

스위프트 코드는 일반적인 프레임 워크 (Foundation, Cocoa, Cocoa Touch 등) 중 하나를 사용할 수 있으며 일반적으로 문자보다 높은 수준의 파일을 읽고 쓸 수있는 많은 방법을 제공합니다 한 번에. 낮은 수준의 파일 I/O를 원할 경우 Martin R.이 제안한대로 NSInputStreamNSOutputStream을 사용하거나 NSData을 사용할 수 있습니다.

물론 평소에 C stdio 기능을 사용하여 파일을 다운 받고 더러운 상태로 만들 수 있습니다. 그러나 물건을 조작 할 때 보통 그런 낮은 수준에서 일하는 것이 타당하지 않습니다.

+1

매우 도움이되는 (그리고 마틴 ​​R) 대답, 수업 시간을 분석해야합니다. – Cheatyx