开发者

How to I read a file in a specific folder with Objective-C?

I am a newbie to Objective-C. Right now, am working on files. My question is.. How do i search for a file in a specific folder ?

Lets say, I get an input string "input". Now all i want to do is search and read the file "input.txt" from a specific path maybe "user/desktop开发者_开发百科/files" folder. How do I do this? I know using NSFileHandle in reading a file by specifying the full path. But I dont know how to do this. Please help me out.

Thanks


There are some NSString methods you should consider using.

// path contains the path to the folder you want to find the file in.

// create the full file name

NSString* shortPath = [@"input" stringByAppendingPathExtension: @"txt"];
NSString* fullPath = [path stringByAppendingPathComponent: shortFileName];

// open the file.  we convert to an NSURL so we can use the better open method
NSURL* fileURL = [NSURL fileURLWithPath: fullPath];
NSError* error = nil;
NSFileHandle *file=[NSFileHandle fileHandleForReadingFromURL: fileURL
                                                       error: &error];
if (file == nil)
{
    // error contains info on what went wrong
}
else
{
    // do what you need
}


In general, to work with paths, you use the following methods which are defined in NSPathUtilities.h (rather than in NSString.h itself):

@interface NSString (NSStringPathExtensions)

+ (NSString *)pathWithComponents:(NSArray *)components;
- (NSArray *)pathComponents;

- (BOOL)isAbsolutePath;

- (NSString *)lastPathComponent;   // frequently-used
- (NSString *)stringByDeletingLastPathComponent;   // frequently-used
- (NSString *)stringByAppendingPathComponent:(NSString *)str;   // frequently-used

- (NSString *)pathExtension;   // frequently-used
- (NSString *)stringByDeletingPathExtension;   // frequently-used
- (NSString *)stringByAppendingPathExtension:(NSString *)str;   // frequently-used

- (NSString *)stringByAbbreviatingWithTildeInPath;
- (NSString *)stringByExpandingTildeInPath;

- (NSString *)stringByStandardizingPath;

- (NSString *)stringByResolvingSymlinksInPath;

- (NSArray *)stringsByAppendingPaths:(NSArray *)paths;

- (NSUInteger)completePathIntoString:(NSString **)outputName
   caseSensitive:(BOOL)flag matchesIntoArray:(NSArray **)outputArray
   filterTypes:(NSArray *)filterTypes;

- (__strong const char *)fileSystemRepresentation;
- (BOOL)getFileSystemRepresentation:(char *)cname maxLength:(NSUInteger)max;

@end

So, you would do something like:

NSString *fullpath = [[path stringByAppendingPathComponent:input]
     stringByAppendingPathExtension:@"txt"];

These methods take care of handling the path separator for you.

If the file is known to be a text file, you can use the following methods in NSString:

- (id)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc
    error:(NSError **)error;
- (id)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc
    error:(NSError **)error;
+ (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc
    error:(NSError **)error;
+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc
    error:(NSError **)error;

/* These try to determine the encoding, and return the encoding which was used.
      Note that these methods might get "smarter" in subsequent releases of the
     system, and use additional techniques for recognizing encodings. If nil
     is returned, the optional error return indicates problem that was 
    encountered (for instance, file system or encoding errors). */
- (id)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc
    error:(NSError **)error;
- (id)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc
    error:(NSError **)error;
+ (id)stringWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc
    error:(NSError **)error;
+ (id)stringWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc
     error:(NSError **)error;

/* Write to specified url or path using the specified encoding.
    The optional error return is to indicate file system or encoding errors.
*/
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFile
    encoding:(NSStringEncoding)enc error:(NSError **)error;
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile
     encoding:(NSStringEncoding)enc error:(NSError **)error;

The latter can be used to write to files.

You'll find many classes in Cocoa have methods to read in from a file or URL themselves. For example, NSImage has a method to read from a file. You can generally think about items at a higher level than file handles (though they do have their place). For generic data, there is always NSData which can also read in from files.

To programmatically get listings of the items in a folder, you can use NSFileManager, then use the methods of NSString to construct paths for individual items.

Oh, another tip if you didn't already know. If you're in an Xcode source code window, hold down the Command key and double-click on any class or method name or data type to open up the header file for that object. For example, Command-double-click on NSString opens up NSString.h. Hold down Command-Option and double-click to open up the Xcode help window and search for the highlighted term.


Ok i just did something with NSString here...

NSString *input=[TextInput stringValue];
NSString *path=@"/Users/mith/Desktop/files/";
NSString *fullpath=[NSString stringWithFormat:@"%@%@.txt",path,input];
NSFileHandle *file=[NSFileHandle fileHandleForReadingAtPath:fullpath];`

Ok now, this works for me fine... But is there a better way to do this ?

Thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜