我有一个包含一系列文本文件的组/文件夹。我需要为每一个获得一条路径,以便我可以阅读内容,但我似乎无法获得任何工作。
我已经和[NSBundle pathsForResourcesOfType:@"txt" inDirectory:@"directoryName"]
混淆了,除了空格或单个字符串,我只读了#34;内容",[[NSFileManager defaultManager] enumeratorAtPath:@"directoryName"]
我不知道该怎么做一旦它被创建,[[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"directoryName" error:nil]
。
我无法弄清楚我做错了什么,而在这一点上,我只是抓住稻草。我在这里经历了20或30页,其中没有一页真的有帮助。
我应该注意到这是一个Cocoa应用程序,而不是iOS。
答案 0 :(得分:3)
如果要读取任意目录中的文件,路径枚举器可以很好地工作。有点老式,但也有它的魅力。
NSString *docPath = @"/tmp";
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:docPath];
NSString *filename;
while ((filename = [dirEnum nextObject])) {
//Do something with the file name
}
如果您想要阅读主目录中众所周知和定义的目录,那么您可以使用NSSearchPathForDirectoriesInDomains
:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths objectAtIndex: 0];
这将为您提供Documents目录,当与上面的代码段一起使用时,列出该文件夹和子文件夹中的所有文件。
请注意,我们不应该再使用我们漂亮的旧Unix路径了,而是引用URL。
在这种情况下,您会得到类似的内容:
NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *docURL = URLs[0];
NSDirectoryEnumerator *URLEnum = [[NSFileManager defaultManager] enumeratorAtURL: docURL includingPropertiesForKeys: nil options: 0 errorHandler: nil];
NSString *filename;
while ((filename = [URLEnum nextObject])) {
// ...
}
请注意,enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:
包含各种有用的参数,您可以在docs中阅读这些参数。
答案 1 :(得分:0)
让我们只拿你的3:
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"directoryName" error:nil]
因此,如果您想要完整路径,您可以这样做:
NSString *directoryPath = ...;
NSArray *fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:...];
for(NSString *fileName in fileNames) {
NSLog(@"%@", [directoryPath stringByAppendingPathComponent:fileName]);
}
答案 2 :(得分:0)
如果您的小组在当前项目中,您可以使用:
NSString *path = [[NSBundle mainBundle] pathForResourcesOfType:@"txt" inDirectory:@"directoryName"]
这应该对你有用,我注意到你尝试过类似的东西,但要确保你使用的是mainBundle。
答案 3 :(得分:0)
问题在于,在添加文件夹时,我还需要创建对该文件夹的引用。 Xcode不默认为此选项。我最初选择简单地创建组,这不起作用。