假设我有一个仅包含 ASCII 字符的 8 字节长的文件:brownfox
。
我不想加载整个文件并处理 if,我不想加载 2 字节的 block [UInt8]
并对 2 字节大小的 block 进行操作,因此操作如下:
- 从文件加载
br
(不是整个文件) - 对数据执行任何操作,例如反转为
rb
- 将输出保存到另一个文件
- 重复:
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/