如何在iOS,模拟器和设备上读/写文件? [英] How to read/write file with iOS, in simulator as well as on device?
问题描述
因为我需要在我的应用程序启动时读取文件并在使用它时有时写入,我试图通过以下方式来访问它:
As I need to read a file when my app is launched and write it sometimes while using it, I tried to reach it with :
NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];
NSLog(@"%@",dataFile);
该文件应该在我的项目文件夹中,而是在模拟器文件夹中:
And the file, that should be in my project folder, is instead in the simulator folder :
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
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
所以,如果我想阅读/使用模拟器和真实设备写它,我该怎么办?
So if I want to read/write it in using the simulator as well as the real device, what should I do ?
感谢您的建议
推荐答案
要从捆绑包中读取文件,请执行以下操作
To read the file from the bundle do the following
NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];
从沙盒存储中读取(文档)
To read it from your sandbox storage (documents)
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];
请注意,您将无法在应用程序的软件包文件夹中写入该文件
Please note you will not be able to write the file in the bundle folder of your application
这篇关于如何在iOS,模拟器和设备上读/写文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!