如何在模拟器和设备上使用 iOS 读/写文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11078647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read/write file with iOS, in simulator as well as on device?
提问by Rob
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-F6474BEEFileApp.txt/MyFileApp.txt/MyFileApp.txt
So if I want to read/write it in using the simulator as well as the real device, what should I do ?
所以如果我想在模拟器和真实设备上读/写它,我该怎么办?
Thanks for your advices
谢谢你的建议
回答by Omar Abdelhafith
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];
To write to document folder
写入文档文件夹
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
请注意,您将无法在应用程序的捆绑文件夹中写入文件
回答by lee
Here is what you need to write and read a file text:
以下是写入和读取文件文本所需的内容:
Write a file:
写一个文件:
-(void) writeStringToFile:(NSString *)aString{
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = @"textFile.txt";
NSString *fileAtPath = [filePath stringByAppendingString:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
and read a file:
并读取一个文件:
-(NSString *)readStringFromFile{
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = @"textFile.txt";
NSString *fileAtPath = [filePath stringByAppendingString:fileName];
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
and finally I test my code at viewDidLoad
:
最后我在viewDidLoad
以下位置测试我的代码:
NSString *text = @"I'm an iOS developer and I'm living at HCM city";
[self writeStringToFile:text];
NSString *strResult = [self readStringFromFile];
NSLog(@"%@", strResult);
回答by Senthilkumar
For write files the methods are -[NSData writeToURL:atomically:]
and -[NSString writeToURL:atomically:encoding:error:]
can be used if you link to the Foundation framework.
对于写入文件,如果您链接到 Foundation 框架-[NSData writeToURL:atomically:]
,-[NSString writeToURL:atomically:encoding:error:]
则可以使用这些方法。
For reading files the methods are -[NSData initWithContentsOfURL:options:error:]
and -[NSString initWithContentsOfURL:encoding:error:]
.
读取文件的方法是-[NSData initWithContentsOfURL:options:error:]
和-[NSString initWithContentsOfURL:encoding:error:]
。
回答by Durul Dalkanat
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) IBOutlet UITextView *txtWriteText;
@property (strong, nonatomic) IBOutlet UIButton *btnWriteFile;
@property (strong, nonatomic) IBOutlet UIButton *btnReadFile;
@property (strong, nonatomic) IBOutlet UILabel *lblReadText;
- (IBAction)btnWriteFileTouched:(id)sender;
- (IBAction)btnReadFileTouched:(id)sender;
@property NSFileManager *filemgr;
@property NSString *docsDir;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_filemgr =[NSFileManager defaultManager];
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
_docsDir = dirPaths[0];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)btnWriteFileTouched:(id)sender {
NSString *filePath = [_docsDir stringByAppendingPathComponent: @"texfile.txt"];
NSData *databuffer = [@"PREFIX: " dataUsingEncoding: NSASCIIStringEncoding];
[_filemgr createFileAtPath: filePath contents: databuffer attributes:nil];
NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath: filePath];
if (file == nil){
NSLog(@"Failed to open file");
return;
}
NSMutableData *data = [NSMutableData dataWithData:[_txtWriteText.text dataUsingEncoding:NSASCIIStringEncoding]];
[file seekToEndOfFile];
[file writeData: data];
[file closeFile];
}
- (IBAction)btnReadFileTouched:(id)sender {
NSString *filePath = [_docsDir stringByAppendingPathComponent: @"texfile.txt"];
NSData *databuffer;
NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath: filePath];
if (file == nil){
NSLog(@"Failed to open file");
return;
}
databuffer = [file readDataToEndOfFile];
[file closeFile];
NSString *datastring = [[NSString alloc] initWithData: databuffer encoding:NSASCIIStringEncoding];
_lblReadText.text = datastring;
}
@end