无法写入文本文件

发布于 2024-11-14 05:34:41 字数 654 浏览 1 评论 0原文

我需要将字符串写入文件。为此,我的代码是:

-(void)writeToFile:(NSString *)fileName: (NSString *)data {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    // the path to write file
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    [data writeToFile:appFile atomically:YES];  
}

我像这样调用这个方法

ownServices *obj = [[ownServices alloc]init];
[obj writeToFile:@"iphone.txt" :@"this is mahesh babu"];

,但它没有写入文本文件。

原因是什么?任何人都可以帮助我吗?

提前谢谢你。

I need to write a string into a file. For that, my code is:

-(void)writeToFile:(NSString *)fileName: (NSString *)data {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    // the path to write file
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    [data writeToFile:appFile atomically:YES];  
}

I am calling this method like this

ownServices *obj = [[ownServices alloc]init];
[obj writeToFile:@"iphone.txt" :@"this is mahesh babu"];

but it didn't write into the text file.

What's the reason? Can anyone please help me.

Thank u in advance.

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

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

发布评论

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

评论(3

逆夏时光 2024-11-21 05:34:41

最有可能的问题是文档目录不存在。如果不存在,则创建它,然后写入它:

NSArray *paths = NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES);
NSString *parentDir = [paths objectAtIndex:0];

/* Create the parent directory.
 * This is expected to fail if the directory already exists. */
(void)[[NSFileManager defaultManager]
       createDirectoryAtPath:parentDir
       withIntermediateDirectories:YES
       attributes:nil error:NULL];
NSString *path = [parentDir stringByAppendingPathComponent:fileName];

/* Now write, and if it fails, you'll know why thanks to the |error| arg. */
NSError *error = nil;
BOOL ok = [data writeToFile:path options:NSDataWritingAtomic error:&error];
if (!ok) {
    NSLog(@"%s: Failed to write to %@: %@", __func__, path, error);
}

更简单的是使用最新的 API,如果该目录尚不存在,它将为您创建该目录:

NSError *error = nil;
NSURL *parentURL = [[NSFileManager defaultManager]
    URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask
    appropriateForURL:nil create:YES error:&error];
if (!parentURL) {
    NSLog(@"%s: *** Failed to get documents directory: %@", __func__, error):
    return;
}

NSURL *furl = [parentURL URLByAppendingPathComponent:fileName];
error = nil;
BOOL ok = [data writeToURL:furl options:NSDataWritingAtomic error:&error];
if (!ok) {
    NSLog(@"%s: *** Failed to write to %@: %@", __func__, furl, error);
}

The most likely problem is that the documents directory does not exist. Create it if it doesn't, then write to it:

NSArray *paths = NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES);
NSString *parentDir = [paths objectAtIndex:0];

/* Create the parent directory.
 * This is expected to fail if the directory already exists. */
(void)[[NSFileManager defaultManager]
       createDirectoryAtPath:parentDir
       withIntermediateDirectories:YES
       attributes:nil error:NULL];
NSString *path = [parentDir stringByAppendingPathComponent:fileName];

/* Now write, and if it fails, you'll know why thanks to the |error| arg. */
NSError *error = nil;
BOOL ok = [data writeToFile:path options:NSDataWritingAtomic error:&error];
if (!ok) {
    NSLog(@"%s: Failed to write to %@: %@", __func__, path, error);
}

Even simpler would be to use the latest API, which will create the directory for you if it doesn't already exist:

NSError *error = nil;
NSURL *parentURL = [[NSFileManager defaultManager]
    URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask
    appropriateForURL:nil create:YES error:&error];
if (!parentURL) {
    NSLog(@"%s: *** Failed to get documents directory: %@", __func__, error):
    return;
}

NSURL *furl = [parentURL URLByAppendingPathComponent:fileName];
error = nil;
BOOL ok = [data writeToURL:furl options:NSDataWritingAtomic error:&error];
if (!ok) {
    NSLog(@"%s: *** Failed to write to %@: %@", __func__, furl, error);
}
脱离于你 2024-11-21 05:34:41

首先,你调用你的方法很奇怪。将方法重命名为

-(void)writeString:(NSString *) data toFile:(NSString *)fileName

并像这样调用它:

[obj writeString:@"this is mahesh babu" toFile:@"iphone.txt"];

其次,不推荐使用 writeToFile:atomically:,使用 writeToFile:atomically:encoding:error:

NSError *error = nil;
BOOL success = [data writeToFile:appFile  atomically:YES encoding:NSUTF8Encoding error:&error];
if (!success) {
    NSLog(@"Error: %@", [error userInfo]);
}

这样,您还可以看到什么错误是。

Firstly, you are calling your method strangely. Rename the method to

-(void)writeString:(NSString *) data toFile:(NSString *)fileName

and call it like so:

[obj writeString:@"this is mahesh babu" toFile:@"iphone.txt"];

Secondly, writeToFile:atomically: is deprecated, use writeToFile:atomically:encoding:error::

NSError *error = nil;
BOOL success = [data writeToFile:appFile  atomically:YES encoding:NSUTF8Encoding error:&error];
if (!success) {
    NSLog(@"Error: %@", [error userInfo]);
}

This way, you also see what the error is.

走过海棠暮 2024-11-21 05:34:41

你的代码看起来没问题。使用调试器(或 NSLog 语句)验证 dataappFile 的值。如果 datanil,则不会发生任何事情(包括没有错误),因为向 nil 发送消息是无操作。也有可能 appFile 不是您认为的路径。

检查您尝试写入的目录的权限 (ls -la)。在设备上不能,但在模拟器上可以。它对您来说是只读的吗?它是否属于其他用户?

假设这不是问题,请尝试使用 atomically:NO 进行调用。原子文件写入是通过写入一个文件,然后重命名它以替换旧文件来执行的。如果问题确实存在,那么就会隔离问题。

Bonus Style Critique

  • 类名应以大写字母开头:OwnServices 而不是 ownServices 尽管
  • 您的方法名称完全有效,但有两个参数且没有单词分隔它们的情况并不常见。像 writeToFile:string: 这样的名称会更好。
  • 如果变量要指向 NSData 以外的实例,请勿将其命名为 data。这很令人困惑,除了“数据”之外,您几乎可以使用一个更好(更具体)的词。

Your code looks OK. Use the debugger (or an NSLog statement) to verify the values of data and appFile. If data is nil, nothing will happen (including no errors) because sending a message to nil is a no-op. It's also possible that appFile is not the path you think it is.

Check the permissions of the directory you are trying to write to (ls -la). On the device you can't, but on the simulator you can. Is it read-only for you? Is it owned by another user?

Assuming that isn't the problem, try calling with atomically:NO. Atomic file writing is performed by writing a file, then renaming it to replace the old one. If the problem is there, that will isolate the problem.

Bonus Style Critique

  • Class names should start with an uppercase letter: OwnServices instead of ownServices
  • Although your method name is perfectly valid, it's unusual to have two parameters with no words to separate them. A name like writeToFile:string: would be better.
  • Don't name a variable data if it is meant to point to an instance of something other than NSData. It's confusing, and there's almost a better (more specific) word you can use beside "data".
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文