如何在iOS,模拟器和设备上读/写文件?

时间:2012-06-18 07:37:25

标签: objective-c ios nsfilemanager read-write

因为我需要在我的应用程序启动时读取文件并在使用它时有时写入,我试图通过以下方式与其联系:

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];
NSLog(@"%@",dataFile);

应该在我的项目文件夹中的文件改为模拟器文件夹:

  

2012-06-13 17:36:56.398 MyFileApp [610:15203] / Users / Rob / Library / Application Support / iPhone Simulator / 5.1 / Applications / 1FFD4436-DCCA-4280-9E47-F6474BEE0183 / MyFileApp.app / MYFILE.TXT

因此,如果我想使用模拟器和真实设备进行读/写,我该怎么办?

感谢您的建议

3 个答案:

答案 0 :(得分:21)

要从捆绑包中读取文件,请执行以下操作

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];

从沙盒存储(文档)中读取它

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
NSString *dataFile = [NSString stringWithContentsOfFile:docPath 
                                           usedEncoding:NSUTF8StringEncoding 
                                                  error:NULL];

写入文件夹

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
[dataFile writeToFile:docPath 
          atomically:YES 
            encoding:NSUTF8StringEncoding 
               error:NULL];

请注意,您将无法在应用程序的软件包文件夹中编写该文件

答案 1 :(得分:2)

以下是编写和阅读文件文本所需的内容:

写一个文件:

-(void) writeStringToFile:(NSString *)aString{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fileName = @"textFile.txt";
    NSString *fileAtPath = [filePath stringByAppendingString:fileName];
    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
        [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
    }
    [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}

并阅读文件:

-(NSString *)readStringFromFile{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fileName = @"textFile.txt";
    NSString *fileAtPath = [filePath stringByAppendingString:fileName];
    return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}

最后我在viewDidLoad测试我的代码:

    NSString *text = @"I'm an iOS developer and I'm living at HCM city";
    [self writeStringToFile:text];
    NSString *strResult = [self readStringFromFile];
    NSLog(@"%@", strResult);

答案 2 :(得分:1)

对于写入文件,方法为-[NSData writeToURL:atomically:],如果链接到Foundation框架,则可以使用-[NSString writeToURL:atomically:encoding:error:]

对于阅读文件,方法为-[NSData initWithContentsOfURL:options:error:]-[NSString initWithContentsOfURL:encoding:error:]