10

由于我需要在启动应用程序时读取文件并有时在使用时写入文件,因此我尝试通过以下方式访问它:

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];
NSLog(@"%@",dataFile);

该文件应该在我的项目文件夹中,而是在模拟器文件夹中:

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

所以如果我想用模拟器和真实设备读/写它,我该怎么办?

感谢您的建议

4

4 回答 4

24

要从包中读取文件,请执行以下操作

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];

从沙盒存储(文档)中读取它

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];

请注意,您将无法在应用程序的 bundle 文件夹中写入文件

于 2012-06-18T07:40:28.557 回答
2

这是您编写和读取文件文本所需的内容:

写一个文件:

-(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];
}

并读取一个文件:

-(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];
}

最后我在以下位置测试我的代码viewDidLoad

    NSString *text = @"I'm an iOS developer and I'm living at HCM city";
    [self writeStringToFile:text];
    NSString *strResult = [self readStringFromFile];
    NSLog(@"%@", strResult);
于 2014-10-29T07:28:07.113 回答
1

对于写入文件,如果您链​​接到 Foundation 框架-[NSData writeToURL:atomically:]-[NSString writeToURL:atomically:encoding:error:]则可以使用这些方法。

读取文件的方法是-[NSData initWithContentsOfURL:options:error:]-[NSString initWithContentsOfURL:encoding:error:]

于 2012-06-18T07:44:25.833 回答
0
#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
于 2015-08-25T06:58:00.990 回答