swift - 如何在 Swift 中从文件(而不是整个文件)中读取数据 block

标签 swift

假设我有一个仅包含 ASCII 字符的 8 字节长的文件:brownfox

我不想加载整个文件并处理 if,我不想加载 2 字节的 block [UInt8] 并对 2 字节大小的 block 进行操作,因此操作如下:

  1. 从文件加载br(不是整个文件)
  2. 对数据执行任何操作,例如反转为 rb
  3. 将输出保存到另一个文件
  4. 重复:ow nf ox

背后的原因: 这样,如果我处理一个 1GB 文本文件,我实际上不必有 1GB 可用 RAM(或 2GB 用于输入和输出文件)。

这种文件处理方法对我来说对于加密和发送到云解决方案很重要。

我正在使用这个扩展:

extension Data {
    /**
     Consumes the specified input stream, creating a new Data object
     with its content.
     - Parameter reading: The input stream to read data from.
     - Note: Closes the specified stream.
     */
    init(reading input: InputStream) {
        self.init()
        input.open()

        let bufferSize = 1024
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
        while input.hasBytesAvailable {
            let read = input.read(buffer, maxLength: bufferSize)
            self.append(buffer, count: read)
        }
        buffer.deallocate()

        input.close()
    }

    /**
     Consumes the specified input stream for up to `byteCount` bytes,
     creating a new Data object with its content.
     - Parameter reading: The input stream to read data from.
     - Parameter byteCount: The maximum number of bytes to read from `reading`.
     - Note: Does _not_ close the specified stream.
     */
    init(reading input: InputStream, for byteCount: Int) {
        self.init()
        input.open()

        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: byteCount)
        let read = input.read(buffer, maxLength: byteCount)
        self.append(buffer, count: read)
        buffer.deallocate()
    }
}

但是 init(reading input: InputStream, for byteCount: Int) 总是从第一个字节开始。例如,我如何读取第 16 到第 20 个字节?

关于InputStream.read(_:maxLength:)的文档

From the current read index, take up to the number of bytes specified in the second parameter from the stream and place them in the client-supplied buffer (first parameter). The buffer must be of the size specified by the second parameter. Return the actual number of bytes placed in the buffer; if there is nothing left in the stream, return 0. Reset the index into the stream for the next read operation.

我该怎么做才能重置索引,并从上一个操作结束的地方获取下一个操作?

最佳答案

使用文件句柄。您可以打开文件句柄进行读取。然后使用 seek(toFileOffset:) 设置您希望读取的位置。然后使用 readData(ofLength:) 获取一些 Data。完成后一定要关闭文件句柄。

关于swift - 如何在 Swift 中从文件(而不是整个文件)中读取数据 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55884381/

相关文章:

ios - Apple Watch 3px 最小左/右填充/边距?

ios - 检测设备是否正在充电或未插电

快速数组初始化

ios - 如何通过在 swift playground 中传递 Int 数组来创建求和函数并调用它?

ios - 如何在 Swift 中启动 iOS 邮件应用程序?

swift - 在 Swift 中禁用自动便利初始化器继承

ios - 无法将类型 'Color' 的值分配给类型 'UIColor'

categories - 从 Swift 访问自定义 Obj-C 类别

ios - 更改 UICollectionView 中选定单元格的文本大小

swift - 具有自定义初始化主体的单例