Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file into array

I have a file of words/phrases separated by newlines. I need to get the file and read each word/phrase into the array. I have this so far:

    NSFileHandle *wordsFile = [NSFileHandle fileHandleForReadingAtPath:[[NSBundle     mainBundle] pathForResource:@"WordList"
                                                                                                           ofType:nil]];
    NSData *words = [wordsFile readDataToEndOfFile];
    [wordsFile closeFile];
    [wordsFile release];

But I'm not sure if that's right, and if so, where to go from there.

Also, teabot's answer of

NSString componentsSeparatedByCharactersInSet: NSCharacterSet newlineCharacterSet

works great, but it's 10.5 only. How would this behavior be replicated for 10.4?

like image 626
Walker Avatar asked Jun 22 '09 13:06

Walker


People also ask

How do you read a file into an ArrayList of objects?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader.

Can JavaScript read files?

Yes JS can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type="file"> .

How do I store a text file in a list in Python?

Example 1: Converting a text file into a list by splitting the text on the occurrence of '. '. We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of the line('/n') with ' ' and split the text further when '.


2 Answers

Here is an approach that should work - I'll leave out an actual code example as the implementation should be fairly straightforward given following:

Construct an NSString from your file with:

NSString stringWithContentsOfFile:encoding:error

Split the string into an array of NSStrings using the following:

NSString componentsSeparatedByCharactersInSet:
NSCharacterSet newlineCharacterSet

You should end up with an NSArray of NSStrings with each string containing one of the lines in your file.

like image 80
teabot Avatar answered Nov 03 '22 08:11

teabot


Just for completeness (and because I am bored) here's a complete example bassed on teabot's post:

    NSString *string = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
                                                            pathForResource:@"file" ofType:@"txt"]];

    NSArray *array = [string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    NSLog(@"%@",array);
like image 42
micmoo Avatar answered Nov 03 '22 09:11

micmoo