"IOS 字节数组转文件内容:在iOS中,可以使用NSData类来操作字节数组和文件之间的转换。\n\n将字节数组转换为文件,可以使用以下方法:\n\nswift\nfunc byteArrayToFile(byteArray: [UInt8], filePath: String) -> Bool {\n let data = Data(byteArray)\n return FileManager.default.createFile(atPath: filePath, contents: data, attributes: nil)\n}\n\n\n使用示例:\n\nswift\nlet byteArray: [UInt8] = [0x48, 0x65, 0x6C, 0x6C, 0x6F] // Hello\nlet filePath = \"path/to/file.txt\"\n\nif byteArrayToFile(byteArray: byteArray, filePath: filePath) {\n print(\"File created successfully\")\n} else {\n print(\"Failed to create file\")\n}\n\n\n将文件转换为字节数组,可以使用以下方法:\n\nswift\nfunc fileToByteArray(filePath: String) -> [UInt8]? {\n if let data = FileManager.default.contents(atPath: filePath) {\n return [UInt8](data)\n }\n return nil\n}\n\n\n使用示例:\n\nswift\nlet filePath = \"path/to/file.txt\"\n\nif let byteArray = fileToByteArray(filePath: filePath) {\n print(\"Byte array: \" + byteArray)\n} else {\n print(\"Failed to read file\")\n}\n\n\n注意:在使用这些方法时,需要确保文件的路径是正确的,并且应用程序有权限读取和写入该文件。

iOS 字节数组与文件转换:Swift 代码示例 - 数据操作教程

原文地址: https://www.cveoy.top/t/topic/p1uU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录