ios文件写不起作用

时间:2016-04-08 13:42:19

标签: ios objective-c nsfilemanager

我想在文件中写一个不起作用的简单数据。

- (void)writeStringToFile:(NSString*)aString {

    // Build the path, and create if needed.
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* fileName = @"bookmark.json";
    NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
    NSLog(@"%@",fileAtPath);
    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
        [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
    }

    // The main act...
    [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:YES];
}

2 个答案:

答案 0 :(得分:0)

您可以修改应用程序的文档目录。

检查文件是否存在于路径

 NSFileManager *fileManager = [NSFileManager defaultManager];
 //Get documents directory
 NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
 (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
 if ([fileManager fileExistsAtPath:@""]==YES) {
     NSLog(@"File exists");
 }    

检查是否可写,可读和可执行

if ([fileManager isWritableFileAtPath:@"FilePath"]) {
    NSLog(@"isWritable");
 }
 if ([fileManager isReadableFileAtPath:@"FilePath"]) {
    NSLog(@"isReadable");
 }
 if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
    NSLog(@"is Executable");
 }

试试这个 Link

快乐编码(^ _ ^)

答案 1 :(得分:0)

试试这样....

  - (void)writeStringToFile:(NSString*)aString {

// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
NSLog(@"%@",fileAtPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
    // The main act...
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:YES];
}}