anon
anon

Reputation:

Reading a text file and turning it into a string

I have added a text file to Xcode, now I want to make a string with it. How do I load it and put it into a string?

NewsStory1.txt is the file, and I'm using Obj-C.

Upvotes: 37

Views: 28261

Answers (5)

Marek Sebera
Marek Sebera

Reputation: 40621

NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

See Apple's iOS API documentation for NSString, specifically the section "Creating and Initializing a String from a File"

Upvotes: 76

dqthe
dqthe

Reputation: 793

Another simpler way with Objective-C:

NSError *error = nil;
NSString *string = [[NSString alloc] initWithContentsOfFile: @"<paht/to/file>"
                     enconding:NSUTF8StringEncoding
                     error: &error];

Upvotes: -1

Maxim Makhun
Maxim Makhun

Reputation: 2231

In Swift 4 this can be done like this:

let path = Bundle.main.path(forResource: "test_data", ofType: "txt")
if let path = path {
    do {
        let content = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
        print(content)
    } catch let error as NSError {
        print("Error occured: \(error.localizedDescription)")
    }
} else {
    print("Path not available")
}

Upvotes: 1

Hassy
Hassy

Reputation: 5208

In swift

let path = NSBundle.mainBundle().pathForResource("home", ofType: "html")

    do {
        let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {}

Upvotes: 5

Rajesh Loganathan
Rajesh Loganathan

Reputation: 11217

Very Simple

Just create a method as follows

- (void)customStringFromFile
{
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
    NSString *stringContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"\n Result = %@",stringContent);
}

Upvotes: 3

Related Questions