【问题标题】:Reading byte array from a file in Objective C从Objective C中的文件中读取字节数组
【发布时间】:2017-12-23 01:37:05
【问题描述】:

我尝试读取包含字节数据的文件。

我的文件读取代码是

    NSString *filepath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"PATH.dat"];    
    NSLog(@"\n\nthe string %@",filepath);
    NSData *fileData = [NSData dataWithContentsOfFile: filepath];
    char *fileBytes = (char *)[fileData bytes];
    NSUInteger length = [fileData length];
    NSLog(@"length %lu", (unsigned long)length);
    NSUInteger index;
    for (index = 0; index<length; index++)
    {
        char aByte = fileBytes[index];
        NSLog(@"byte %d", aByte);
    }

以下输出显示文件路径正常,但长度为 0。

the string /var/containers/Bundle/Application/6D84F701-BC0E-43AD-8FD8-1F0083CE1F84/ProductName.app/PATH.dat
2017-12-22 17:54:18.746773+0800 ProductName[8704:2173252] length 0

我的文件读取有什么问题?

编辑:

if([[NSFileManager defaultManager] fileExistsAtPath: filepath])
        NSLog(@"fileexist");

【问题讨论】:

  • 您能否事先检查[[NSFileManager defaultManager] fileExistsAtPath: filepath] 是否返回true?如果您将自己的文件添加到您的包中,该怎么做:NSString *filepath= [[NSBundle mainBundle] pathForResource:@"PATH" ofType:@"dat"];?
  • @Larme 我在 EDIT 中添加。但是没有作为文件存在的输出。这意味着文件不存在?我将文件作为右键单击项目/将文件添加到项目选项。
  • Y 我检查了构建阶段/复制捆绑资源。我在那里找到了文件。
  • 是的,它有效。谢谢你。我的问题是文件名拼写错误。

标签: ios objective-c


【解决方案1】:

尝试使用它来获取文件的路径:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"FILENAME" ofType:@"dat"];

如果还是不行,试试:

NSURL *fileUrl = [NSURL fileURLWithPath:filepath];
NSData *fileData = [NSData dataWithContentsOfURL:fileUrl];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2012-10-05
    • 2023-03-20
    相关资源
    最近更新 更多