NSFileHandle fileHandleForWritingAtPath:返回 null!

发布于 2024-09-18 03:51:13 字数 470 浏览 7 评论 0原文

我的 iPad 应用程序有一个小型下载工具,我想使用 NSFileHandle 附加数据。问题是创建调用仅返回空文件句柄。可能是什么问题?这是应该创建文件句柄的三行代码:

NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName]; 
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];

我检查了文件路径,没有发现任何问题。

泰亚

my iPad app has a small download facility, for which I want to append the data using an NSFileHandle. The problem is the creation call only returns null file handles. What could be the problem? Here is the three lines of code that are supposed to create my file handle:

NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName]; 
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];

I checked the file path, and I could see nothing wrong.

TYIA

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情释 2024-09-25 03:51:13

fileHandleForWritingAtPath 不是“创建”调用。文档明确指出:“返回值:初始化的文件句柄,如果路径中不存在文件,则nil”(添加了强调)。如果您希望在文件不存在的情况下创建该文件,则必须使用类似以下的内容:

 NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 if(output == nil) {
      [[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
      output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 }

如果您想追加到该文件(如果它已存在),请使用类似 [outputeekToEndOfFile] 的内容。您的完整代码将如下所示:

 NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
 self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName]; 
 NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 if(output == nil) {
      [[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
      output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 } else {
      [output seekToEndOfFile];
 }

fileHandleForWritingAtPath is not a “creation” call. The documentation explicitly states: “Return Value: The initialized file handle, or nil if no file exists at path” (emphasis added). If you wish to create the file if it does not exist, you’d have to use something like this:

 NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 if(output == nil) {
      [[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
      output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 }

If you want to append to the file if it already exists, use something like [output seekToEndOfFile]. Your complete code would then look as follows:

 NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
 self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName]; 
 NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 if(output == nil) {
      [[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
      output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 } else {
      [output seekToEndOfFile];
 }
请持续率性 2024-09-25 03:51:13

获取文档目录路径

+(NSURL *)getDocumentsDirectoryPath
{
    return [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
}

将文本保存到文件末尾

如果文件不存在,则创建该文件并

+(void)saveText:(NSString *)textTobeSaved atPath:(NSString*)fileName
{
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName];
    
    NSString *path = [[self getDocumentsDirectoryPath].path
                      stringByAppendingPathComponent:filePath];
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    if(fileHandler == nil) {
        [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
        fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    } else {
        textTobeSaved = [NSString stringWithFormat:@"\n-----------------------\n %@",textTobeSaved];
        [fileHandler seekToEndOfFile];
    }
    
    [fileHandler writeData:[textTobeSaved dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandler closeFile];
}

使用指定的文件名写入数据从文件中获取文本

+(NSString *)getTextFromFilePath:(NSString *)fileName
{
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName];
    
    NSString *path = [[self getDocumentsDirectoryPath].path
                      stringByAppendingPathComponent:filePath];
    NSLog(@"%@",path);
    if(path!=nil)
    {
    NSString *savedString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    return savedString;
  }else{
    return @"";
  } 
}

>删除文件

+(void)deleteFile:(NSString *)fileName
{
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName];
    
    NSString *path = [[self getDocumentsDirectoryPath].path
                      stringByAppendingPathComponent:filePath];
    
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    if(fileHandler != nil) {
        [[NSFileManager defaultManager]removeItemAtPath:path error:nil];
    }
    
}

Get documents directory path

+(NSURL *)getDocumentsDirectoryPath
{
    return [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
}

Save text to end of the file

if file doesnt exist create it and write data

+(void)saveText:(NSString *)textTobeSaved atPath:(NSString*)fileName
{
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName];
    
    NSString *path = [[self getDocumentsDirectoryPath].path
                      stringByAppendingPathComponent:filePath];
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    if(fileHandler == nil) {
        [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
        fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    } else {
        textTobeSaved = [NSString stringWithFormat:@"\n-----------------------\n %@",textTobeSaved];
        [fileHandler seekToEndOfFile];
    }
    
    [fileHandler writeData:[textTobeSaved dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandler closeFile];
}

get text from file with specified filename

+(NSString *)getTextFromFilePath:(NSString *)fileName
{
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName];
    
    NSString *path = [[self getDocumentsDirectoryPath].path
                      stringByAppendingPathComponent:filePath];
    NSLog(@"%@",path);
    if(path!=nil)
    {
    NSString *savedString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    
    return savedString;
  }else{
    return @"";
  } 
}

Delete file

+(void)deleteFile:(NSString *)fileName
{
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName];
    
    NSString *path = [[self getDocumentsDirectoryPath].path
                      stringByAppendingPathComponent:filePath];
    
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    if(fileHandler != nil) {
        [[NSFileManager defaultManager]removeItemAtPath:path error:nil];
    }
    
}
心凉怎暖 2024-09-25 03:51:13

初始化程序 API 已更改,但这对其他人来说仍然可能有用。
我正在使用 FileHandle(forReadingAtPath: String) 初始化程序,当我意识到:

  • 在使用 fileURL.absoluteString 作为路径时,初始化程序返回 nil (绝对字符串看起来像 file:///Users/xyz/Library/.../Containers/Data/Application/...file.MP4
  • 初始化程序使用 fileURL.relativePath 正常工作 的路径(相对路径看起来像 /Users/xyz/Library/.../Containers/Data/Application/...file.MP4

基本上, FileHandler 初始化程序更喜欢相对路径而不是绝对字符串。

The initialiser APIs have changed, but this still might be useful for other people.
I was using the FileHandle(forReadingAtPath: String) initialiser, when I realised that:

  • The initialiser returned nil while using fileURL.absoluteString for the path (absolute string looks like file:///Users/xyz/Library/.../Containers/Data/Application/...file.MP4
  • The initialiser worked correctly using fileURL.relativePath for the path. (relative path looks like /Users/xyz/Library/.../Containers/Data/Application/...file.MP4)

Basically, the FileHandler initialiser prefers the relative path over the absolute string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文