简体   繁体   English

无法写入文本文件

[英]Not able to write into text file

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.提前谢谢你。

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:更简单的是使用最新的 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);
}

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: :其次,不推荐使用 writeToFile:atomically 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]);
}

This way, you also see what the error is.这样,您还可以看到错误是什么。

Your code looks OK.您的代码看起来不错。 Use the debugger (or an NSLog statement) to verify the values of data and appFile .使用调试器(或NSLog语句)来验证dataappFile的值。 If data is nil , nothing will happen (including no errors) because sending a message to nil is a no-op.如果datanil ,则不会发生任何事情(包括没有错误),因为向nil发送消息是无操作的。 It's also possible that appFile is not the path you think it is. appFile也可能不是您认为的路径。

Check the permissions of the directory you are trying to write to ( ls -la ).检查您尝试写入的目录的权限( 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 .假设这不是问题,请尝试使用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 Class 名称应以大写字母开头: OwnServices而不是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.writeToFile:string:这样的名称会更好。
  • Don't name a variable data if it is meant to point to an instance of something other than NSData .如果变量data旨在指向NSData以外的某个实例,请不要命名它。 It's confusing, and there's almost a better (more specific) word you can use beside "data".这很令人困惑,除了“数据”之外,您几乎可以使用一个更好(更具体)的词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM