iPhonec 中怎么读取txt文件从Application Bundle中读取文件

iOS学习笔记21—从文本文件中读取内容到字符串里
NSString *textFileContents = [NSString
stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:@&myTextFile&
ofType:@&txt&]
encoding:NSUTF8StringEncoding
error: & error];
// If there are no results, something went wrong
if (textFileContents == nil) {
// an error occurred
NSLog(@&Error reading text file. %@&, [error localizedFailureReason]);
NSArray *lines = [textFileContents componentsSeparatedByString:@&&];
NSLog(@&Number of lines in the file:%d&, [lines count] );runtime 获取设备上所有App的bundle id - 简书
runtime 获取设备上所有App的bundle id
include &objc/runtime.h&
使用下面代码获取设备上安装应用的bundle id
Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
NSObject* workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
NSLog(@"apps: %@", [workspace performSelector:@selector(allApplications)]);
结果如下:
" com.apple.Passbook",
" com.apple.GameController",
" com.apple.MailCompositionService",
" com.apple.calculator",
" com.apple.SharedWebCredentialViewService",
" com.apple.ios.StoreKitUIService",
" com.apple.MobileStore",
" com.apple.tips",
" com.apple.camera",
" com.apple.quicklook.quicklookd",
" com.apple.webapp",
" passCalibrationViewService",
" com.apple.iad.iAdOptOut",
" com.apple.MusicUIService",
" com.apple.WebContentFilter.remoteUI.WebContentAnalysisUI",
" com.apple.mobilesms.notification",
" com.pose",
" com.apple.Fitness",
" com.apple.videos",
" com.apple.social.SLGoogleAuth",
" com.apple.mobileslideshow",
" com.apple.Health",
" com.apple.purplebuddy",
" com.apple.AccountAuthenticationDialog",
" com.apple.AdSheetPhone",
" com.apple.Diagnostics",
" com.apple.Maps",
" com.apple.PrintKit.Print-Center",
" com.apple.iBooks",
" com.apple.mobilecal",
" com.apple.MobileSMS",
" com.apple.uikit.PrintStatus",
" com.apple.CloudKit.ShareBear",
" com.apple.Music",
" com.apple.podcasts",
" com.apple.fieldtest",
" com.apple.HealthPrivacyService",
" com.apple.FacebookAccountMigrationDialog",
" com.apple.iosdiagnostics",
" com.apple.AskPermissionUI",
" com.apple.AppStore",
" com.apple.Bridge",
" com.apple.mobilesafari",
" com.apple.weather",
" com.apple.gamecenter",
" com.apple.appleaccount.AACredentialRecoveryDialog",
" com.apple.PhotosViewService",
" com.apple.facetime",
" com.apple.VoiceMemos",
" com.apple.mobilenotes",
" com.apple.Preferences",
" com.apple.mobilephone",
" com.apple.share",
" com.apple.reminders",
" com.apple.mobiletimer",
" com.apple.TencentWeiboAccountMigrationDialog",
" com.apple.MobileAddressBook",
" com.apple.CoreAuthUI",
" com.apple.datadetectors.DDActionsService",
" com.apple.PassbookUIService",
" com.apple.TrustMe",
" com.apple.family",
" com.apple.webapp1",
" com.apple.appleseed.FeedbackAssistant",
" com.apple.InCallService",
" com.apple.WebSheet",
" com.apple.mobilemail",
" com.apple.stocks",
" com.apple.gamecenter.GameCenterUIService",
" com.apple.PreBoard",
" com.apple.SiriViewService",
" com.apple.DemoApp",
" com.apple.WebViewService",
" com.booltinteam.tinynote",
" com.chunyu.SymptomChecker",
" com.netease.videoHD",
" me.imtx.TomatoTimer",
" com.codality.NotationalFlow",
" com.dajie.djapp",
" com.evernote.iPhone.Evernote",
" com.yongche.iYongche",
" ch.noidentity.Next",
" com.realmacsoftware.clear",
" com.jianshu.Hugo",
" com.taobao.tmall",
" com.apple.itunesu",
" com.kapeli.dashios",
" de.floriankugler.objcio",
" com.shiningtrip.wochacha4",
" com.apple.itunesconnect.mobile",
" me.imtx.NewLime",
" com.codeorgana.brushstroke",
" com.tencent.sosomap",
" com.huxiu",
" com.taobao.taobao4iphone",
" com.gpl.dailycost",
" com.dajie.PositionInvitation",
" com.apple.Keynote",
" com.netease.mailmaster",
" com.xiami.spark",
" com.xiaojukeji.didi",
" com.kingsoft.powerwordBeta",
" cn.geili.IShopping2",
" com.vstudio.camera360",
" com.autohome.quote",
" com.amazon.Lassen",
" com.tencent.mqq",
" com.autonavi.amap",
" com.tencent.ioshlddz",
" com.stackexchange.stackexchange",
" com.brixd.Nice-Wallpaper",
" com.lede.trainticket",
" com.acqualia.soulver-iPhone",
" com.netease.cloudmusic",
" com.bluerhino.client",
" cn.dxy.aspirinpro",
" com.tiantian.-684--",
" com.leanpub.Leanpub",
" com.duokan.reader",
" com.apple.Pages",
" com.ideashower.ReadItLaterPro",
" com.cmbchina.MPBBank",
" com.apple.bird.SharedPackageExtensions",
" com.culturedcode.ThingsTouch",
" com.flexibits.fantastical2.iphone",
" cn.12306.rails12306",
" com.chinaunicom.mobilebusiness",
" com.openet.gtgj",
" com.burbn.instagram",
" com.sina.weibo",
" com.onlyway.Train",
" com.baidu.waimai",
" com.khanov.Symbols",
" fm.overcast.overcast",
" com.eicodesign.weibopro",
" de.dennisreimann.iOctocat2",
" com.apple.Numbers",
" com.cmbchina.cmblife",
" eusoft.eudic.pro",
" com.youdao.bigbangEnglish",
" cn.com.admaster.SurveyPrize",
" com.apple.mobileme.fmip1",
" me.chriscsc.LongScreen",
" com.dayonelog.dayoneiphone",
" com.moke.moke-2",
" com.dajie.sjmq",
" au.com.shiftyjelly.podcasts",
" com.funcity.taxi",
" io.manong.DeveloperDaily",
" com.taofang.iphone",
" com.ifttt.ifttt",
" youdaoPro",
" com.amazon.AmazonCN",
" com.ordinaryfactory.analogfilm",
" com.xinniangshuo.iphone",
" com.mchina.hbh",
" com.reederapp.rkit2.ios",
" com.gtja.yhtkh",
" com.quora.app.mobile",
" com.itouchchina.chinametro",
" com.hooks.hooks",
" com.6wunderkinder.wunderlistmobile",
" com.auramarker.zine",
" com.tencent.xin",
" com.tapbots.Tweetbot3",
" com.squaremountains.PeekCalendar",
" com.baidu.map",
" com.autohome",
" com.360buy.jdmobile",
" com.meituan.imeituan",
" com.ninjinkun.webviewprogress.DemoApp",
" com.tangyumeng.WeakDemo",
" com.vipshop.iphone",
" com.Fingertip",
" com.openet.gtgj (Placeholder)",
" com.apple.MobileReplayer",
" com.qunar.iphoneclient8",
" com.brixd.niceapps",
" com.zhihu.ios",
" com.mukewang.mukewang",
" com.sf-express.waybilltracking",
" cn.rafood.rubychina",
" com.letv.iphone.client",
" com.lofocus.doubandushu",
" com.douban.read.iphone",
" com.souyidai.investment",
" com.baidu.tieba",
" com.aibang.bus",
" iss.HunBoHui",
" com.weico.weicopro4",
" dativestudios.DSLCalendarViewExample",
" cn.yunlai.hunbohui",
" com.chanyouji.Birth",
" com.alipay.iphoneclient",
" com.tencent.qqmail",
" com.tianqu.ChinaMetro",
" com.dianping.dpscope",
" com.xueqiu",
" com.jiemian.news",
" com.fingertip"读取文件内容到NSString
读取文件内容到NSString,我使用以下代码
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@&push实现.txt&];&&&&
&& NSError* err=&
&& NSString* mTxt=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&err];&
&& NSLog(@&err:%@&,err);&
&& NSLog(@&filePath:%@&,filePath);&
&& NSLog(@&mTxt:%@&,mTxt);&
&NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@&push实现.txt&];&&
&&& NSError* err=
&&& NSString* mTxt=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&err];
&&& NSLog(@&err:%@&,err);
&&& NSLog(@&filePath:%@&,filePath);
&&& NSLog(@&mTxt:%@&,mTxt);
出错了,log为:
12:35:36.374 Paging[] err:Error Domain=NSCocoaErrorDomain Code=261 &The operation couldn&t be completed. (Cocoa error 261.)& UserInfo=0x8868b00 {NSFilePath=/Users/ericyang/Library/Application Support/iPhone Simulator/6.1/Applications/A3D216E7-DC10-48C3-AD40-C069/Paging.app/push实现.txt, NSStringEncoding=4}&
12:35:36.375 Paging[] filePath:/Users/ericyang/Library/Application Support/iPhone Simulator/6.1/Applications/A3D216E7-DC10-48C3-AD40-C069/Paging.app/push实现.txt&
12:35:36.375 Paging[] mTxt:(null)&
12:35:36.374 Paging[] err:Error Domain=NSCocoaErrorDomain Code=261 &The operation couldn&t be completed. (Cocoa error 261.)& UserInfo=0x8868b00 {NSFilePath=/Users/ericyang/Library/Application Support/iPhone Simulator/6.1/Applications/A3D216E7-DC10-48C3-AD40-C069/Paging.app/push实现.txt, NSStringEncoding=4}
12:35:36.375 Paging[] filePath:/Users/ericyang/Library/Application Support/iPhone Simulator/6.1/Applications/A3D216E7-DC10-48C3-AD40-C069/Paging.app/push实现.txt
12:35:36.375 Paging[] mTxt:(null)
找到原因,是编码问题,我的文件应该是GBK的,修改代码:
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@&push实现.txt&];&&&&
&& unsigned long encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_);&&&&&
&& NSData *responseData = [NSData dataWithContentsOfFile:filePath];&
&& NSString *mTxt = [[NSString alloc] initWithData:responseData encoding:encode];&
&& NSLog(@&filePath:%@&,filePath);&
&& NSLog(@&mTxt:%@&,mTxt);&
&NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@&push实现.txt&];&&
&&& unsigned long encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_);&&&
&&& NSData *responseData = [NSData dataWithContentsOfFile:filePath];
&&& NSString *mTxt = [[NSString alloc] initWithData:responseData encoding:encode];
&&& NSLog(@&filePath:%@&,filePath);
&&& NSLog(@&mTxt:%@&,mTxt);
ok,正常打印。iOS加载并显示bundle的.txt文件的方法
- (void)jiazaitxt{
self.myWebview = [[UIWebView
alloc]initWithFrame:CGRectMake(0,
0, [UIScreen
mainScreen].bounds.size.width, [UIScreen
mainScreen].bounds.size.height+60)];
myWebView.delegate =
//NSString
*path = [NSString stringWithFormat:@"%@/Documents/附件/%@",NSHomeDirectory(),self.wendangnaem];
NSString *txtPath=[[NSBundle
mainBundle]pathForResource:@"city_list"
ofType:@"txt"];
NSLog(@"txtPath:%@",txtPath);
///编码可以解决 .txt
中文显示乱码问题
NSStringEncoding *useEncodeing =
//带编码头的如utf-8等,这里会识别出来
NSString *body = [NSString
stringWithContentsOfFile:txtPath
usedEncoding:useEncodeing error:nil];
//识别不到,按GBK编码再解码一次.这里不能先按GB18030解码,否则会出现整个文档无换行bug。
if (!body) {
body = [NSString
stringWithContentsOfFile:txtPath encoding:0x
error:nil];
NSLog(@"%@",body);
//还是识别不到,按GB18030编码再解码一次.
if (!body) {
body = [NSString
stringWithContentsOfFile:txtPath encoding:0x
error:nil];
NSLog(@"%@",body);
if (body) {
NSLog(@"%@",body);
NSData *data=[body
dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data:%@",data);
id userData=[NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingMutableContainers
error:nil];
if (userData) {
if ([userData isKindOfClass:[NSDictionary
{"code":"000000","memo":"成功",
{"domestic":
[{"cityId":"110100","cityName":"北京市","region":[{"regionId":"110101","regionName":"北京市-东城区"},{"regionId":"110102","regionName":"北京市-西城区"},{"regionId":"110103","regionName":"北京市-崇文区"},{"regionId":"110105","regionName":"北京市-朝阳区"},{"regionId":"110106","regionName":"北京市-丰台区"},
NSArray *domesticArray=[(NSDictionary *)userData
objectForKey:@"domestic"];
for (NSDictionary *dict
in domesticArray)
QSSMyMessageNowCityModel *model=[[QSSMyMessageNowCityModel
alloc]init];
[self.myWebview
loadHTMLString:body
baseURL: nil];
NSString *urlString = [[NSBundle
mainBundle] pathForAuxiliaryExecutable:txtPath];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *requestUrl = [NSURL
URLWithString:urlString];
NSLog(@"%@",urlString);
NSURLRequest *request = [NSURLRequest
requestWithURL:requestUrl];
[self.myWebview
loadRequest:request];
addSubview:self.myWebview];数据的存储无疑是软件开发中的重要课题。本文给初学者介绍下iphone开发中常见的文件读写
iOS的文件存储采用的是“沙箱机制”,也就是应用程序只能访问自己的文件目录,每个应用程序的数据是独立的,就像一个一个的沙箱一样。这种管理方法比windows和原来的塞班那种文件管理方式更适合移动平台。这种方式更安全,在很大程度上避免了流氓软件和垃圾软件的盗窃资料。
查看模拟器应用程序在mac上的存储,就可以了解在iphone上文件是如何组织的。
打开目录/Users/andy/Library/Application Support/iPhone Simulator/5.1/Applications就会看到模拟器上的程序文件夹,你会看到iphone每个应用程序都有自己的3个目录(Document,Library,tmp)
Documents存放应用程序的数据。
Library目录下面还有Preferences和Caches目录,Preferences目录存放应用程序的使用偏好,Caches目录与Documents很相 是可以存放应用程序的数据。
tmp目录供应用程序存储临时文件。
注意,如果你的设置没有设置为查看隐藏目录,你是看不到的,设置显示隐藏文件方法:在终端输入命令:defaults write com.apple.finder AppleShowAllFiles -bool true然后重启下finder。&
在应用程序中获得自己的documents目录:
NSArray *&paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString * documentDirectory = [paths objectAtIndex:0];
在上面的基础上,获得一个完整的文件路径和名字:
NSString * file = [documentDirectory stringByAppendingPathComponent:@&file1.txt&];
这就可以用file来创建,读取,和写入文件。
iOS中数据存储常见的有四种方式: 属性列表、对象归档、ios嵌入式数据库(SQLite3)和Core Data(苹果提供的工具)
一,用属性列表保存数据:
该方法就是针对一些集合类调用writeToFile:atomically方法和initWithContentsOfFile 方法来写入和读取数据。
这些集合类包括:NSArray,NSMutableArray,NSDictionary,NSMutableDictionary,NSData,NSMutableData,NSString,NSMutableString,NSNumber,NSDate。在这里输入代码太麻烦了,无法识别回车换行,所以这个就不在这里举例了。
二,归档方法保存自定义对象:
属性列表方法简单易用,但是使用有局限性,就是无法保存自定义的数据类。要解决这个问题,我们看归档方法。归档方法实际就是 用 NSKeyedArchiver 对 自定义类进行编解码成 NSMutableData 后,再对NSMutableData实行序列化具体的编解码是由NSCoder实现的。举个例子就比较容易掌握。
例子中我们保存4个值和一个名字字典。这些名字包括昵称,qq网名,微博网名,省份证名字。自定义类如下:
#import &Foundation/Foundation.h&&&
&BIDFourLines : NSObject&
@property (copy, nonatomic) NSString *field1;&
@property (copy, nonatomic) NSString *field2;&
@property (copy, nonatomic) NSString *field3;&
@property (copy, nonatomic) NSString *field4;&
@property (copy, nonatomic) NSDictionary *&
实现文件:
#import &BIDFourLines.h&&
#define kField1Key @&Field1&&
#define kField2Key @&Field2&&
#define kField3Key @&Field3&&
#define kField4Key @&Field4&&
#define kFieldArrayKey @&FieldArray&
#pragma mark NSCoding&
- (void)encodeWithCoder:(NSCoder *)encoder {&
&[encoder encodeObject:field1 forKey:kField1Key];&
[encoder encodeObject:field2 forKey:kField2Key];&
[encoder encodeObject:field3 forKey:kField3Key];&
[encoder encodeObject:field4 forKey:kField4Key];&
[encoder encodeObject:names forKey:kFieldArrayKey];&
- (id)initWithCoder:(NSCoder *)decoder {&
if (self = [super init]) {&
field1 = [decoder decodeObjectForKey:kField1Key];&
field2 = [decoder decodeObjectForKey:kField2Key];&
field3 = [decoder decodeObjectForKey:kField3Key];&
field4 = [decoder decodeObjectForKey:kField4Key];&
names = [decoder decodeObjectForKey:kFieldArrayKey];&
- (id)copyWithZone:(NSZone *)zone {&
BIDFourLines *copy = [[[self class] allocWithZone: zone] init];&
copy.field1 = [self.field1 copyWithZone:zone];&
copy.field2 = [self.field2 copyWithZone:zone];&
copy.field3 = [self.field3 copyWithZone:zone];&
copy.field4 = [self.field4 copyWithZone:zone];&
copy.names = [self.names copyWithZone:zone];&
保存文件代码:&
- (void) saveTofile{&
BIDFourLines *fourLines = [[BIDFourLines alloc] init];&
fourLines.field1 = field1.&
fourLines.field2 = field2.&
fourLines.field3 = field3.&
fourLines.field4 = field4.&
fourLines.names = [NSDictionary dictionaryWithObjectsAndKeys:@&andy&,@&nickName&,@&王勃&,@&idName&,@&田鼠&,@&qqName&,@&大力哥&,@&weiboName&,nil ]; NSMutableData *data = [[NSMutableData alloc] init];&
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];&
[archiver encodeObject:fourLines forKey:kDataKey];&
[archiver finishEncoding];&
[data writeToFile:[self dataFilePath] atomically:YES];&
获取文件名函数:&
- (NSString *)dataFilePath {&
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);&
NSString *documentsDirectory = [paths objectAtIndex:0];&
return [documentsDirectory stringByAppendingPathComponent:@&archive&];&
- (void) loadFileData{&
NSString *filePath = [self dataFilePath];&
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {&
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];&
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];&
BIDFourLines *fourLines = [unarchiver decodeObjectForKey:kDataKey];&
[unarchiver finishDecoding];&
field1.text = fourLines.field1;&
field2.text = fourLines.field2;&
field3.text = fourLines.field3;&
field4.text = fourLines.field4;&
NSDictionary * names = fourLines.&
if(names) {&
NSArray * array = [names allKeys];&
& for (NSString * value in array) {&
& & &NSLog(@&%@ is %@&,value,[names objectForKey:value]);&
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:182163次
积分:2027
积分:2027
排名:千里之外
原创:28篇
评论:70条
文章:11篇
阅读:97095
(1)(1)(4)(15)(4)(1)(2)(2)(1)(5)
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'}

我要回帖

更多关于 c 读取文件中的数据 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信