您的当前位置:首页正文

文件读取

来源:花图问答

1、判断文件是否存在
NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Doucment/save"];
NSFileManager *filemanager = [NSFileManager defaultManager];
BOOL isExist = [filemanager fileExistsAtPath:filePath];

2、复制文件到沙盒
//复制数据库到沙盒下;不能手动拖拽到沙盒下,因为拖过去的前提是沙盒存在;沙盒存在的前提是程序运行起来;难道你的软件用户下载之后,自己找到沙盒,找到数据库,把数据库拖到沙盒下吗?

//把数据库复制一分到沙盒下
-(void)copyDataBaseToSandBox{
//目的路径
NSString * path = [NSHomeDirectory() stringByAppendingString:@"/Documents/database.sqlite"];
NSLog(@"%@",path);
//源路径
NSString *sourcePath = [[NSBundle mainBundle]pathForResource:@"database" ofType:@"sqlite"];
//复制操作
NSFileManager * fileManager = [NSFileManager defaultManager];
//目的路径下,没有这个文件
if (! [fileManager fileExistsAtPath:path]){
//复制
[fileManager copyItemAtPath:sourcePath toPath:path error:nil];
}
}

3、拼接文件夹路径
+(NSString *)getFilePathWithDirectoryName:(NSString *)directoryName fileName:(NSString *)fileName{
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

// 拼接文件夹路径 判断 保证文件夹一定存在
NSString *directoryPath = [NSString stringWithFormat:@"%@/%@",path,directoryName];

if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath]){
    [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
}
// 拼接一个完整的文件路径 返回
NSString *filePath = [NSString stringWithFormat:@"%@/%@",directoryPath,fileName];   
return filePath;

}

4、plist文件
NSArray *provinces = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"area.plist" ofType:nil]];(看取的数据类型(或NSDictionary)创建

5、图片
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"png"];
UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];

6、音频、视频
// 音频播放。支持AAC,AMR,ALAC,iLBC,IMA4,PCM,MP3
// 播放本地音频
NSString *localAudioPath = [[NSBundle mainBundle] pathForResource:@"Music" ofType:@"mp3"];
// 创建一个本地的url
NSURL *localAudioURL = [NSURL fileURLWithPath:localAudioPath];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:localAudioURL error:nil];
// 播放网络音频
// NSURL *netAudioURL = [NSURL URLWithString:@"hello.mp3"];
// audioPlayer = [[AVAudioPlayer alloc] initWithData:[NSData dataWithContentsOfURL:netAudioURL] error:nil];

转换为NSData
NSData *mediaData = [NSData dataWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:@"file://localhost/private%@", _mp4Path(文件路径)]]];//