Object-c:兩種文件讀寫的對比

 

1、讀寫方法對比:(主要針對本地讀取本地文件)
方式\操做
非URL方式

stringWithContentsOfFilehtml

writeToFile安全

URL方式

stringWithContentsOfURL網絡

writeToURLapp

實際開發中,大部分都採用URL方式。
對於寫入操做,狀況都是:若是文件存在,則覆蓋原文件中的內容;若是文件不存在,則建立一個新文件
 
2、非URL方式
1.比較陌生的是文件寫入的方法中,會有個atomically參數。
   atomically(原子性):設置YES時,沒有寫完,則會所有撤銷(比較安全的作法)。
                                         設置NO時,沒有寫完,不會撤銷。
2.NSError對象,能夠經過localizedDescription方法獲取報錯信息。
 
 
例子:
//
//  main.m
//  字符串練習2:讀寫文件
//
//  Created by Apple on 15/12/7.
//  Copyright © 2015年 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
void readFile(NSString *path);
void writeToFile(NSString *path, NSString *str);

int main(int argc, const char * argv[]) {
    //讀取文件中的內容
    //NSString *path1 = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/字符串練習2:讀寫文件/1.txt";
    NSString *path1 = @"/Users/apple/Desktop/1.txt";
    NSLog(@"讀取文件:");
    readFile(path1);

    //寫入文件內容
    NSString *path2 = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/字符串練習2:讀寫文件/2.txt";
    NSLog(@"寫入文件");
    NSString *str = @"這是一個測試";
    writeToFile(path2,str);

    NSLog(@"讀取文件:");
    readFile(path2);

    return 0;
}

 

//讀取文件
void readFile(NSString *path){
    NSError *error = nil;
    NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    if (error != nil) {
        NSLog([error localizedDescription]);//將錯誤信息輸出來
    }
    else{
        NSLog(@"%@",str);
    }
}
//寫入文件
void writeToFile(NSString *path, NSString *str){
    NSError *error = nil;
    //atomically : YES時,沒有寫完,則會所有撤銷;NO時候,沒有寫完,不會撤銷
    //注意:這種寫入方式,若是文件補存在,則建立;若是文件存在,則覆蓋原文件的內容
    BOOL flag = [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];//通常error都設置爲nil,保證寫入成功
    if (flag) {
        NSLog(@"寫入成功");
    }
    else{
        NSLog(@"寫入失敗");
    }
}
 
3、URL方式
URL方式,根據URL對象的建立方式,又分爲兩種:
一.經過 URLWithString方法建立URL對象
1)路徑:協議 + ip + 文件路徑
訪問本地資源:file:// + ip + /文件路徑
訪問網絡資源:http:// + ip + /文件路徑
注意:(1)讀取本地資源的時候,ip地址能夠省略,即:file:///文件路徑(ip地址後面/不能省略,表明着根路徑)
         (2)路徑中若是包含中文的時候,須要使用stringByAddingPercentEscapesUsingEncoding方法或stringByAddingPercentEncodingWithAllowedCharacters方法進行路徑進行編碼,否則,會提示:The file couldn’t be opened because the specified URL type isn’t supported.(URL類型不支持)
 
例如:
NSString *path = @"file://192.168.1.103/Users/apple/Desktop/讀寫文件練習2/1.txt」;
//NSString *path = @"file:///Users/apple/Desktop/讀寫文件練習2/1.txt」;
//path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//比較老的方法,如今被下面的方法取代
path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

NSURL *url = [NSURL URLWithString:path];

NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

if (error == nil) {
    NSLog(@"%@",str);
}
else{
        NSLog(@"%@",[error localizedDescription]);
} 
 
二.經過 fileURLWithPath方法建立URL對象,訪問本地資源

使用這個方法時,須要注意:測試

     1)系統會幫咱們自動加入file://,咱們不須要再添加。再添加,路徑就不對了。this

     2)即便URL中包含中文,均可以訪問。系統會自動對包含的中文進行處理。因此通常開發中,訪問本地資源,都使用這個方法。編碼

 
例子:
NSString *path = @"/Users/apple/Desktop/讀寫文件練習2/1.txt」;
 
NSURL *url = [NSURL fileURLWithPath:path];

NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

if (error == nil) {
    NSLog(@"%@",str);
}
else{
    NSLog(@"%@",[error localizedDescription]);
}
 
3、綜合例子:
//
//  main.m
//  讀寫文件練習2
//
//  Created by Apple on 15/12/7.
//  Copyright © 2015年 Apple. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    //一.文件讀取
    //路徑使用URL
    //1.加載本地文件。注意:file://,不是file:///
    NSString *path = @"file://192.168.1.103/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/讀寫文件練習2/1.txt";

    //若是加載的是本地資源,那麼URL上的主機地址能夠不要
    //注意:ip地址後面的斜槓不能省略!(其表明着跟路徑)
    //path = @"file:///Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/讀寫文件練習2/1.txt";

    //若是路徑中包含中文,先進行編碼
    //不編碼的後果是:The file couldn’t be opened because the specified URL type isn’t supported.(URL類型不支持)
    //path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//比較老的方法,如今被下面的方法取代
    //path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    //2.加載網絡資源
    //path = @"http://www.baidu.com";

    //NSURL *url = [NSURL URLWithString:path];

    //3.使用fileURLWithPath建立URL對象,加載本地資源。
    /*
     使用這個方法時,須要注意:
     1)系統會幫咱們自動加入file://,咱們不須要再添加。再添加,路徑就不對了。
     2)即便URL中包含中文,均可以訪問。系統會自動對包含的中文進行處理。因此通常開發中,訪問本地資源,都使用這個方法。
     */
    path = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/讀寫文件練習2/1.txt";
    NSURL *url = [NSURL fileURLWithPath:path];

    NSError *error = nil;
    
    NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    if (error == nil) {
        NSLog(@"%@",str);
    }
    else{
        NSLog(@"%@",[error localizedDescription]);
    }


    //二.文件寫入
    //路徑使用URL
    NSError *error2 = nil;
    NSString *str2 = @"this is a test2";

    /*
    //第一種方式
    NSString *path2 =@"file:///Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/讀寫文件練習2/2.txt";
    path2 = [path2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"path2 = %@",path2);
    NSURL *url2 = [NSURL URLWithString:path2];
    */

    //第二種方式
    NSString *path2 = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/讀寫文件練習2/2.txt";
    NSURL *url2 = [NSURL fileURLWithPath:path2];

    //注意:若是文件存在,則覆蓋原文件的內容;若是文件不存在,則新建
    [str2 writeToURL:url2 atomically:YES encoding:NSUTF8StringEncoding error:&error2];
    if (error2 != nil) {
        NSLog(@"%@", [error2 localizedDescription]);
    }
    else{
        NSLog(@"文件寫入成功!");
    }

    return 0;
}

 

 
推薦閱讀:
相關文章
相關標籤/搜索