【问题标题】:Cycle through a directory and get paths of all the files and folders [closed]循环浏览目录并获取所有文件和文件夹的路径[关闭]
【发布时间】:2013-09-12 01:31:07
【问题描述】:

您好,我卡在这件事上,我需要循环访问某个 dir,我需要从中获取所有文件名并将路径作为变量获取。

我知道如何创建循环,但要获取目录的内容,我不知道。

感谢任何帮助,谢谢!

【问题讨论】:

  • 看看 NSFileManager 类里面有一些方法可以帮助你。
  • 我知道 NSFileManager,我只是坚持如何使用它来获取文件的路径
  • `enumeratorAtPath:'(例如)这没有告诉你什么吗?该文档甚至有示例代码
  • 你可以阅读 NSFileManager 的文档。请注意,它有一个执行操作的方法列表。其中一些返回文件列表等。

标签: macos cocoa loops file-management


【解决方案1】:

试试这样:

// If your folder is a document.
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:  @"Documents"];
// else you can give your folder path as well, if you know 
// for example like this NSString *docsDir = @"user/desktop/testFolder"

NSFileManager *localFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
NSString *file = nil;
NSData *fileContents = [NSData data];
while ((file = [dirEnum nextObject])) 
{
   NSLog(@"your file name%@",file); // This will give your filename
   // Now for getting file path follow below.
   // here we are adding path to filename.
   NSString *fileNamePath = [docsDir stringByAppendingPathComponent:file];
   NSLog(@"your fileNamePath%@",fileNamePath); // This will give your filename path
   fileContents = [NSData dataWithContentsOfFile:fileNamePath]; // This will store file contents in form of bytes

}

希望对你有帮助:)

【讨论】:

  • 我不知道为什么这得到了 2 张反对票,但这对我很有帮助!谢谢! +1
  • @hussain-shabbir 我用这样的路径尝试了你的解决方案 @"/Users/myUser/Downloads/" 但 dirEnum 总是返回 nil。你知道为什么吗?
  • 只是通过下载并检查??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2017-07-22
  • 1970-01-01
相关资源
最近更新 更多