今天就本周作業(yè)的讀取txt文件查找了的一些方法,如下:
//讀取文本內(nèi)容
NSError *error;
NSString *txt = [NSString stringWithContentsOfFile:@"<本地文件名>" encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"讀取文件出錯(cuò):%@", error);
return;
}
//計(jì)算文本占用的尺寸
UIFont *txtFont = [UIFont systemFontOfSize:11];
CGSize size = CGSizeMake(250.0f,2000.0f);
CGSize labelsize = [txt sizeWithFont:txtFont constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
//把文本寫到UILabel控件里
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 22, labelsize.width,labelsize.height)];
contentLabel.backgroundColor = [UIColor clearColor];
contentLabel.tag = 12346;
contentLabel.numberOfLines = 0;
contentLabel.font = txtFont;
contentLabel.lineBreakMode = UILineBreakModeWordWrap;
contentLabel.text = txt;
NSString類提供了很多方法來(lái)從文件或者URL中讀取數(shù)據(jù).通常情況下,你是知道文件的編碼的,讀取數(shù)據(jù)就很容易.如果你有一個(gè)文本(plaintext), 但是不知道它的編碼, 那就有點(diǎn)困難了.
從已知編碼的文件讀取數(shù)據(jù)可以使用 stringWithContentsOfFile
:encoding:error 或者相應(yīng)的init函數(shù) (initWithContentsOfFile:encoding:error)
如果使用不指定編碼的stringWithContentsOfFile: 來(lái)讀取文件, 可能會(huì)丟失信息或者損壞數(shù)據(jù)
對(duì) 于未知編碼的文件最好的方法是保證有一種機(jī)制來(lái)糾正不可避免的錯(cuò)誤. 比如,Apple的Mail和Safari應(yīng)用有個(gè)菜單,TextEdit也允許用戶用指定的編碼重新打開文件.如果你想在缺少編碼信息的情況下,猜出 編碼,可以使用
stringWithContentsOfFile:usedEncoding:error:或者 initWithContentsOfFile:encoding:error: 方法
例如:
NSString *str=[NSString stringWithContentsOfFile:@"/Users/stjy/Desktop/zhudongxue/oc部分/oc自己練習(xí)/查找本地文件內(nèi)容/查找本地文件內(nèi)容/File1" encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",str);
NSString *str2=[[NSString alloc]initWithContentsOfFile:@"/Users/stjy/Desktop/zhudongxue/oc部分/oc自己練習(xí)/查找本地文件內(nèi)容/查找本地文件內(nèi)容/File1"encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",str2);
這 幾個(gè)方法將猜試 資源的編碼,如果成功,就通過(guò)引用返回使用的編碼.如果失敗,就默認(rèn)使用UTF-8的編碼如果再次失敗,就使用一種合適的古老編碼, “合適”的意思,在這里依賴環(huán)境,它可能是默認(rèn)的C String編碼,也可能是Windows Latin1編碼
最后,你還可以試試用 NSAttributedString’ 方法 來(lái)猜編碼
stringWithContentsOfFile: 方法如果內(nèi)容以Unicode的BOM開始(U+FEFF或者U+FFFE),那么解釋這個(gè)文本內(nèi)容為Unicode 字符.如果以UTF-8的BOM(EFBBBF)開始, 就解釋為UTF-8否則,默認(rèn)將內(nèi)容解釋為C字符串.
因?yàn)槟J(rèn)的C String編碼可能會(huì)隨著用戶的配置而改變, 除非你使用Unicode或者UTF-8編碼,否則就不要使用這種方法
相 對(duì)于從文件讀取數(shù)據(jù),寫是比較簡(jiǎn)單的writeToFile:atomically:encoding:error:你必須指定應(yīng)該使用的編碼,選擇 是否自動(dòng)寫資源如果你不選擇自動(dòng)寫入, 內(nèi)容被直接寫入到指定的文件. 否則,首先寫到一個(gè)輔助文件,然后輔助文件被改名為指定的文件.iphone讀取文本文件
iOS學(xué)習(xí)之NSBundle介紹和使用
1、使用類方法創(chuàng)建一個(gè)NSBundle對(duì)象
+ (NSBundle *)mainBundle;
eg:[NSBundle mailBundle];
2、使用路徑獲取一個(gè)NSBundle 對(duì)象,這個(gè)路徑應(yīng)該是一個(gè)目錄的全路徑
+ (NSBundle *)bundleWithPath:(NSString *)path;
eg:
NSString *path = [mailBundle resourcePath];
NSBundle *language = [NSBundle bundleWithPath:path];
3、使用路徑初始化一個(gè)NSBundle
- (id)initWithPath:(NSString *)path;
4、使用一個(gè)url 創(chuàng)建并初始化一個(gè)NSBundle對(duì)象(這是一個(gè)類方法)
注:這里的url 是一個(gè)特殊的 文件url路徑
+ (NSBundle *)bundleWithURL:(NSURL *)url
5、使用一個(gè)url 初始化一個(gè)NSBundle對(duì)象
注:這里的url 是一個(gè)特殊的 文件url路徑
- (id)initWithURL:(NSURL *)url
6、根據(jù)一個(gè)特殊的class 獲取NSBundle
+ (NSBundle *)bundleForClass:(Class)aClass;
eg:根據(jù)當(dāng)前的class 獲取一個(gè)NSBundle // 獲取當(dāng)前類的NSBundle
NSBundle *bud = [NSBundle bundleForClass:[self class]];
NSLog(@"bud==%@",bud);
輸出結(jié)果如下:
NSBundle
7、獲取特定名稱的bundle
+ (NSBundle *)bundleWithIdentifier:(NSString *)identifier;
8、使用NSBundle 獲取所有的bundle信息(由于ios安全沙盒的限制,所有的獲取的資源,是應(yīng)用程序的資源)
注:官方標(biāo)注,獲取所有的非framework 的bundle;
+ (NSArray *)allBundles;
eg:
NSArray *array = [NSBundle allBundles];
NSLog(@"array===%@",array);
打印的結(jié)果如下:
array===(
"NSBundle? (loaded)"
)
9、獲取應(yīng)用程序加載的所有framework的資源,
+ (NSArray *)allFrameworks;
eg:
NSArray *array = [NSBundle allFrameworks];
NSLog(@"%@",array);
輸出的結(jié)果如下:(
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)",
"NSBundle? (loaded)"
)
10、判斷bundle 加載,(按照官方文檔,You don’t need to load a bundle’s executable code to search the bundle’s resources.我們不需要調(diào)用這個(gè)方法,)
- (BOOL)load;
11、判斷bundle 加載
- (BOOL)isLoaded;
12、判斷bundle 加載
- (BOOL)unload;
13、加載資源,如果有錯(cuò)誤的話,會(huì)放置錯(cuò)誤信息
- (BOOL)preflightAndReturnError:(NSError **)error
- (BOOL)loadAndReturnError:(NSError **)error
14、獲取bundle 類實(shí)例的 url
- (NSURL *)bundleURL
15、獲取bundle 類實(shí)例的 resourceUrl 資源
- (NSURL *)resourceURL
16、獲取bundle 類實(shí)例的 可執(zhí)行的URL
- (NSURL *)executableURL
17、(Returns the file URL of the executable with the specified name in the receiver’s bundle.返回一個(gè),文件的URL,使用一個(gè)特殊的名稱)
- (NSURL *)URLForAuxiliaryExecutable:(NSString *)executableName
18、獲取當(dāng)前NSBundle實(shí)例的 URL 資源
- (NSURL *)privateFrameworksURL
19、獲取共享的frameworkdURL
- (NSURL *)sharedFrameworksURL
20、 獲取支持的Bundle的Url
- (NSURL *)sharedSupportURL
21、獲取添加插件的URL
- (NSURL *)builtInPlugInsURL
// 已經(jīng)不能使用,
- (NSURL *)appStoreReceiptURL
22、 獲取bundle 的path 路徑
- (NSString *)bundlePath;
23、獲取bundle 的資源路徑字符串
- (NSString *)resourcePath;
24、獲取bundle 可執(zhí)行文件路徑
- (NSString *)executablePath;
25、獲取bundle 輔助的path
- (NSString *)pathForAuxiliaryExecutable:(NSString *)executableName;
26、獲取私有的路徑框架
- (NSString *)privateFrameworksPath;
27、獲取共享的framework path 路徑
- (NSString *)sharedFrameworksPath;
28、獲取共享的路徑
- (NSString *)sharedSupportPath;
29、獲取插件的路徑
- (NSString *)builtInPlugInsPath;
// 已經(jīng)廢棄,不能調(diào)用
+ (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext subdirectory:(NSString *)subpath inBundleWithURL:(NSURL *)bundleURL
// 已經(jīng)廢棄
+ (NSArray *)URLsForResourcesWithExtension:(NSString *)ext subdirectory:(NSString *)subpath inBundleWithURL:(NSURL *)bundleURL
30、使用bundle 創(chuàng)建一個(gè)資源文件的URL
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext
eg:
NSURL* URL=[[NSBundle mainBundle] URLForResource:fileName withExtension:@"png"];
31、(官方描述如下:Returns the file URL for the resource file identified by the specified name and extension and residing in a given bundle directory.
使用資源文件的名稱以及擴(kuò)展名,還有子路徑)
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext subdirectory:(NSString *)subpath
32、(官方描述:
Returns the file URL for the resource identified by the specified name and file extension,
located in the specified bundle subdirectory, and limited to global resources and those associated with the specified localization.)
同上一個(gè)方法,不同的是添加了本地資源文件的信息
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext subdirectory:(NSString *)subpath localization:(NSString *)localizationName
33、根據(jù)文件的后綴名稱和子目錄,獲取一個(gè)NSURL 的數(shù)組
- (NSArray *)URLsForResourcesWithExtension:(NSString *)ext subdirectory:(NSString *)subpath
34、同上面的方法,添加了本地化的一個(gè)資源文件
- (NSArray *)URLsForResourcesWithExtension:(NSString *)ext subdirectory:(NSString *)subpath localization:(NSString *)localizationName
35、根據(jù)資源文件的名稱,或者是文件的后綴名稱以及目錄的路徑,獲取 path
+ (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)bundlePath;
36、根據(jù)文件的擴(kuò)展名,以及資源的路徑,獲取一個(gè)數(shù)組
+ (NSArray *)pathsForResourcesOfType:(NSString *)ext inDirectory:(NSString *)bundlePath;
37、根據(jù)文件的名稱和擴(kuò)展名獲取 path 名稱
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext;
37、根據(jù)文件的名稱和擴(kuò)展名獲取 path 名稱
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)subpath;
37、根據(jù)文件的名稱和擴(kuò)展名獲取 path 名稱
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)subpath forLocalization:(NSString *)localizationName;
38、根據(jù)文件的擴(kuò)展名和子目錄獲取一個(gè)資源文件的數(shù)組
- (NSArray *)pathsForResourcesOfType:(NSString *)ext inDirectory:(NSString *)subpath;
39、同上,添加了資源文件的一個(gè)路徑
- (NSArray *)pathsForResourcesOfType:(NSString *)ext inDirectory:(NSString *)subpath forLocalization:(NSString *)localizationName;
40、方法調(diào)用解釋如下
- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName NS_FORMAT_ARGUMENT(1);
你可以通過(guò)NSBundle來(lái)找到對(duì)應(yīng)key值的vaule.
NSBundle *main = [NSBundle mainBundle];
NSString *aString = [main localizedStringForKey:@"Key1"
value:@"DefaultValue1"
table:@"Find"];
上面的代碼會(huì)在Find.strings中查找"Key1"對(duì)應(yīng)的vuale字符串. 如果沒(méi)有提供用戶指定的語(yǔ)言的本地化資源,那么就會(huì)查找第二個(gè)所選語(yǔ)言,如果第二個(gè)也沒(méi)有本地化資源,就依次找下去. 如果到最后還是沒(méi)有找到,那么 ""DefaultValue1"將會(huì)返回
// 返回當(dāng)前bundle的唯一標(biāo)示:(即:應(yīng)用的唯一標(biāo)示)
- (NSString *)bundleIdentifier;
eg:com.company.ios-Example-NSBundle.IOS-Example-NSBundle
// 獲取資源文件的dictionary 對(duì)象
- (NSDictionary *)infoDictionary;
eg:
{
CFBundleDevelopmentRegion = en;
CFBundleDisplayName = "IOS_Example_NSBundle";
CFBundleExecutable = "IOS_Example_NSBundle";
CFBundleExecutablePath = "/Users/ctrip1/Library/Application Support/iPhone Simulator/6.1/Applications/2F3DA58F-5CF9-48A2-ADB2-C923A29B519E/IOS_Example_NSBundle.app/IOS_Example_NSBundle";
CFBundleIdentifier = "com.company.ios-Example-NSBundle.IOS-Example-NSBundle";
CFBundleInfoDictionaryVersion = "6.0";
CFBundleInfoPlistURL = "Info.plist -- file://localhost/Users/ctrip1/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/2F3DA58F-5CF9-48A2-ADB2-C923A29B519E/IOS_Example_NSBundle.app/";
CFBundleName = "IOS_Example_NSBundle";
CFBundlePackageType = APPL;
CFBundleShortVersionString = "1.0";
CFBundleSignature = "????";
CFBundleSupportedPlatforms =? ? (
iPhoneSimulator
);
CFBundleVersion = "1.0";
DTPlatformName = iphonesimulator;
DTSDKName = "iphonesimulator6.1";
LSRequiresIPhoneOS = 1;
NSBundleInitialPath = "/Users/ctrip1/Library/Application Support/iPhone Simulator/6.1/Applications/2F3DA58F-5CF9-48A2-ADB2-C923A29B519E/IOS_Example_NSBundle.app";
NSBundleResolvedPath = "/Users/ctrip1/Library/Application Support/iPhone Simulator/6.1/Applications/2F3DA58F-5CF9-48A2-ADB2-C923A29B519E/IOS_Example_NSBundle.app";
UIDeviceFamily =? ? (
1,
2
);
UIRequiredDeviceCapabilities =? ? (
armv7
);
UISupportedInterfaceOrientations =? ? (
UIInterfaceOrientationPortrait,
UIInterfaceOrientationLandscapeLeft,
UIInterfaceOrientationLandscapeRight
);
}
41、返回本地化資源的NSDictionary 對(duì)象
- (NSDictionary *)localizedInfoDictionary;
42、根據(jù)key 值獲取本地化資源對(duì)象的值
- (id)objectForInfoDictionaryKey:(NSString *)key;
43、(官方描述:Returns the Class object for the specified name.根據(jù)類名字符串獲取一個(gè)類對(duì)象)
- (Class)classNamed:(NSString *)className;
44、返回主要的類
- (Class)principalClass;
45、返回本地化資源的列表
- (NSArray *)localizations;
46、本地化的語(yǔ)言列表
- (NSArray *)preferredLocalizations;
47、使用創(chuàng)建的類獲取本地化語(yǔ)言
- (NSString *)developmentLocalization;
48、(官方描述 Returns one or more localizations from the specified list that a bundle object would use to locate resources for the current user.)
+ (NSArray *)preferredLocalizationsFromArray:(NSArray *)localizationsArray;
+ (NSArray *)preferredLocalizationsFromArray:(NSArray *)localizationsArray forPreferences:(NSArray *)preferencesArray;
iOS學(xué)習(xí)之NSBundle介紹和使用
bundle是一個(gè)目錄,其中包含了程序會(huì)使用到的資源.這些資源包含了如圖像,聲音,編譯好的代碼,nib文件(用戶也會(huì)把bundle稱為plug-in).對(duì)應(yīng)bundle,
cocoa提供了類NSBundle.
我們現(xiàn)在用bundle獲取程序里的一張圖片,并顯示到View上。
新建一個(gè)Single View Application,并在加入viewDidLoad方法里加入如下代碼:
//? ? 通過(guò)使用下面的方法得到程序的main bundle
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *imagePath = [mainBundle pathForResource:@"QQ20120616-1" ofType:@"png"];
NSLog(@"%@", imagePath);
UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath];
UIImageView? *imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
在項(xiàng)目上右鍵,add圖片文件圖片文件QQ20120616.png。
運(yùn)行程序:
打印出來(lái)圖片路徑如下
/Users/rongfzh/Library/Application Support/iPhone Simulator/5.1/Applications/3B8EC78A-5EEE-4C2F-B0CB-4C3F02B996D2/iOSSandbox.app/QQ20120616-1.png
我們可以看到,圖片在iOSSandbox.app這個(gè)包里,
NSBundle mainBundle讀取文件夾下的文件夾列表
NSArray *array = [[NSBundle mainBundle] pathsForResourcesOfType:@"jpg" inDirectory:@"image"];
NSLog(@"array:%@",array);
首先需要在mac上新建一個(gè)文件夾叫image, 放一些圖片進(jìn)去,然后把整個(gè)文件夾拖到項(xiàng)目中,在彈出的對(duì)話框中選擇:Create folder references for any added folders ,這個(gè)會(huì)創(chuàng)建一個(gè)真實(shí)的目錄,否則找到不這個(gè)目錄下的文件
家目錄下共有四個(gè)子目錄:
Documents 目錄:您應(yīng)該將所有的應(yīng)用程序數(shù)據(jù)文件寫入到這個(gè)目錄下。這個(gè)目錄用于存儲(chǔ)用戶數(shù)據(jù)或其它應(yīng)該定期備份的信息。
AppName.app 目錄:這是應(yīng)用程序的程序包目錄,包含應(yīng)用程序的本身。由于應(yīng)用程序必須經(jīng)過(guò)簽名,所以您在運(yùn)行時(shí)不能對(duì)這個(gè)目錄中的內(nèi)容進(jìn)行修改,否則可能會(huì)使應(yīng)用程序無(wú)法啟動(dòng)。
Library 目錄:這個(gè)目錄下有兩個(gè)子目錄:Caches 和 Preferences
Preferences 目錄包含應(yīng)用程序的偏好設(shè)置文件。您不應(yīng)該直接創(chuàng)建偏好設(shè)置文件,而是應(yīng)該使用NSUserDefaults類來(lái)取得和設(shè)置應(yīng)用程序的偏好
Caches 目錄用于存放應(yīng)用程序?qū)S玫闹С治募4鎽?yīng)用程序再次啟動(dòng)過(guò)程中需要的信息。
tmp 目錄:這個(gè)目錄用于存放臨時(shí)文件,保存應(yīng)用程序再次啟動(dòng)過(guò)程中不需要的信息。
獲取這些目錄路徑的方法:
1,獲取家目錄路徑的函數(shù):
NSString *homeDir = NSHomeDirectory();
2,獲取Documents目錄路徑的方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
3,獲取Caches目錄路徑的方法:
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
4,獲取tmp目錄路徑的方法:
NSString *tmpDir = NSTemporaryDirectory();
5,獲取應(yīng)用程序程序包中資源文件路徑的方法:
例如獲取程序包中一個(gè)圖片資源(apple.png)路徑的方法:
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”apple” ofType:@”png”];
UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
代碼中的mainBundle類方法用于返回一個(gè)代表應(yīng)用程序包的對(duì)象。
文件IO
1,將數(shù)據(jù)寫到Documents目錄:
- (BOOL)writeApplicationData:(NSData *)data toFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0]; if (!docDir) { NSLog(@”Documents directory not found!”); return NO; }
NSString *filePath = [docDir stringByAppendingPathComponent:fileName];
return [data writeToFile:filePath atomically:YES];}
2,從Documents目錄讀取數(shù)據(jù):
- (NSData *)applicationDataFromFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:fileName];
NSData *data = [[[NSData alloc] initWithContentsOfFile:filePath] autorelease]; return data;}
NSSearchPathForDirectoriesInDomains這個(gè)主要就是返回一個(gè)絕對(duì)路徑用來(lái)存放我們需要儲(chǔ)存的文件。
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"shoppingCar.plist"];
}
NSFileManager* fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:[self dataFilePath]]){
//下面是對(duì)該文件進(jìn)行制定路徑的保存
[fm createDirectoryAtPath:[self dataFilePath] withIntermediateDirectories:YES attributes:nil error:nil];
//取得一個(gè)目錄下得所有文件名
NSArray *files = [fm subpathsAtPath: [self dataFilePath] ];
//讀取某個(gè)文件
NSData *data = [fm contentsAtPath:[self dataFilePath]];
//或者
NSData *data = [NSData dataWithContentOfPath:[self dataFilePath]];
}