ios 如何检查文档文件夹中是否存在文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1638834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:34:00  来源:igfitidea点击:

How to check if a file exists in Documents folder?

iosiphonexcodewebviewnsfilemanager

提问by Obliviux

I have an application with In-App Purchase, that when the user buy something, download one html file into the Documents folder of my app.

我有一个应用程序内购买的应用程序,当用户购买东西时,将一个 html 文件下载到我的应用程序的 Documents 文件夹中。

Now I must check if this HTML file exists, so if true, load this HTML file, else load my default html page.

现在我必须检查此 HTML 文件是否存在,如果为真,则加载此 HTML 文件,否则加载我的默认 html 页面。

How I can do that? With NSFileManagerI can't get outside of mainBundle..

我怎么能做到这一点?随着NSFileManager我无法离开mainBundle..

回答by Nikolai Ruhe

Swift 3:

斯威夫特 3:

let documentsURL = try! FileManager().url(for: .documentDirectory,
                                          in: .userDomainMask,
                                          appropriateFor: nil,
                                          create: true)

... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:

... 为您提供文档目录的文件 URL。以下检查是否有名为 foo.html 的文件:

let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)

Objective-C:

目标-C:

NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

回答by orkoden

Apple recommends against relying on the fileExistAtPath: method. It's often better to just try to open a file and deal with the error if the file does not exist.

Apple 建议不要依赖 fileExistAtPath: 方法。如果文件不存在,最好尝试打开文件并处理错误。

NSFileManager Class Reference

Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.

NSFileManager 类参考

注意:不建议尝试根据文件系统的当前状态或文件系统上的特定文件来预测行为。这样做会导致奇怪的行为或竞争条件。尝试操作(例如加载文件或创建目录)、检查错误并优雅地处理这些错误比尝试提前确定操作是否会成功要好得多。有关文件系统竞争条件的更多信息,请参阅安全编码指南中的“竞争条件和安全文件操作”。

Source: Apple Developer API Reference

来源:Apple Developer API 参考

From the secure coding guide.

来自安全编码指南。

To prevent this, programs often check to make sure a temporary file with a specific name does not already exist in the target directory. If such a file exists, the application deletes it or chooses a new name for the temporary file to avoid conflict. If the file does not exist, the application opens the file for writing, because the system routine that opens a file for writing automatically creates a new file if none exists. An attacker, by continuously running a program that creates a new temporary file with the appropriate name, can (with a little persistence and some luck) create the file in the gap between when the application checked to make sure the temporary file didn't exist and when it opens it for writing. The application then opens the attacker's file and writes to it (remember, the system routine opens an existing file if there is one, and creates a new file only if there is no existing file). The attacker's file might have different access permissions than the application's temporary file, so the attacker can then read the contents. Alternatively, the attacker might have the file already open. The attacker could replace the file with a hard link or symbolic link to some other file (either one owned by the attacker or an existing system file). For example, the attacker could replace the file with a symbolic link to the system password file, so that after the attack, the system passwords have been corrupted to the point that no one, including the system administrator, can log in.

为了防止这种情况,程序通常会检查以确保目标目录中不存在具有特定名称的临时文件。如果存在这样的文件,应用程序将删除它或为临时文件选择一个新名称以避免冲突。如果该文件不存在,则应用程序打开该文件进行写入,因为如果不存在,则打开文件进行写入的系统例程会自动创建一个新文件。攻击者通过持续运行一个程序来创建一个具有适当名称的新临时文件,可以(有一点持久性和一些运气)在应用程序检查以确保临时文件不存在之间的间隙中创建文件当它打开它进行写作时。然后应用程序打开攻击者的文件并写入其中(请记住,系统例程打开一个现有文件(如果有),并仅在没有现有文件时创建一个新文件)。攻击者的文件可能与应用程序的临时文件具有不同的访问权限,因此攻击者可以读取内容。或者,攻击者可能已经打开了该文件。攻击者可以使用指向其他文件(攻击者拥有的文件或现有系统文件)的硬链接或符号链接替换该文件。例如,攻击者可以将文件替换为指向系统密码文件的符号链接,这样在攻击之后,系统密码已被破坏到包括系统管理员在内的任何人都无法登录的程度。s 文件可能与应用程序的临时文件具有不同的访问权限,因此攻击者可以读取内容。或者,攻击者可能已经打开了该文件。攻击者可以使用指向其他文件(攻击者拥有的文件或现有系统文件)的硬链接或符号链接替换该文件。例如,攻击者可以将文件替换为指向系统密码文件的符号链接,这样在攻击之后,系统密码已被破坏到包括系统管理员在内的任何人都无法登录的程度。s 文件的访问权限可能与应用程序的临时文件不同,因此攻击者可以读取其中的内容。或者,攻击者可能已经打开了该文件。攻击者可以使用指向其他文件(攻击者拥有的文件或现有系统文件)的硬链接或符号链接替换该文件。例如,攻击者可以将文件替换为指向系统密码文件的符号链接,这样在攻击之后,系统密码已被破坏到包括系统管理员在内的任何人都无法登录的程度。攻击者可以使用指向其他文件(攻击者拥有的文件或现有系统文件)的硬链接或符号链接替换该文件。例如,攻击者可以将文件替换为指向系统密码文件的符号链接,这样在攻击之后,系统密码已被破坏到包括系统管理员在内的任何人都无法登录的程度。攻击者可以使用指向其他文件(攻击者拥有的文件或现有系统文件)的硬链接或符号链接替换该文件。例如,攻击者可以将文件替换为指向系统密码文件的符号链接,这样在攻击之后,系统密码已被破坏到包括系统管理员在内的任何人都无法登录的程度。

回答by John Riselvato

If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking

如果您以不同的方式设置文件系统或寻找不同的方式来设置文件系统,然后检查文档文件夹中是否存在文件,这里是另一个示例。还显示动态检查

for (int i = 0; i < numberHere; ++i){
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
    NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
    if (fileExists == NO){
        cout << "DOESNT Exist!" << endl;
    } else {
        cout << "DOES Exist!" << endl;
    }
}

回答by Tal Zion

Swift 2.0

斯威夫特 2.0

This is how to check if the file exists using Swift

这是使用 Swift 检查文件是否存在的方法

func isFileExistsInDirectory() -> Bool {
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDirectory: AnyObject = paths[0]
    let dataPath = documentsDirectory.stringByAppendingPathComponent("/YourFileName")

    return NSFileManager.defaultManager().fileExistsAtPath(dataPath)
}

回答by Mani

check if file exist in side the document/catchimage path :

检查文件/catchimage 路径中是否存在文件:

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 
}

回答by iOS

NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath =  [directoryPath objectAtIndex:0];
//If you have superate folder
imagePath= [imagePath stringByAppendingPathComponent:@"ImagesFolder"];//Get docs dir path with folder name
_imageName = [_imageName stringByAppendingString:@".jpg"];//Assign image name
imagePath= [imagePath stringByAppendingPathComponent:_imageName];
NSLog(@"%@", imagePath);

//Method 1:
BOOL file = [[NSFileManager defaultManager] fileExistsAtPath: imagePath];
if (file == NO){
    NSLog("File not exist");
} else {
    NSLog("File exist");
}

//Method 2:
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
if (!(image == nil)) {//Check image exist or not
    cell.photoImageView.image = image;//Display image
}

回答by DawnSong

NSURL.h provided - (BOOL)checkResourceIsReachableAndReturnError:(NSError **)errorto do so

NSURL.h 提供- (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error这样做

NSURL *fileURL = [NSURL fileURLWithPath:NSHomeDirectory()];
NSError * __autoreleasing error = nil;
if ([fileURL checkResourceIsReachableAndReturnError:&error]) {
    NSLog(@"%@ exists", fileURL);
} else {
    NSLog(@"%@ existence checking error: %@", fileURL, error);
}

Or using Swift

或者使用 Swift

if let url = URL(fileURLWithPath: NSHomeDirectory()) {
    do {
        let result = try url.checkResourceIsReachable()
    } catch {
        print(error)
    }
}