Home > database >  How to read only first part of a file in Swift?
How to read only first part of a file in Swift?

Time:11-07

Reading a file into memory as bytes is easy:

let fileURL: URL = ...
Data(contentsOf: fileURL)

But that returns everything. I want to look at the first 16 bytes of a file, without loading the rest into memory. What's the best way to do this in Swift?

CodePudding user response:

Use the FileHandle API, which has read(upToCount:):

let handle = try FileHandle(forReadingFrom: someURL)
let first16Bytes: Data? = try handle.read(upToCount: 16)
try handle.close()

Alternatively, you can read the file asynchronously, in which case you can control how many bytes you read by moving the iterator forward (calling AsyncIterator.next), or use prefix to get the first bytes.

  • Related