如何从巨大的文本文件中读取文本块?
我正在尝试读取包含数十亿字符的文本文件。使用功能 contentOfFile
无法正常工作,因为我的应用程序因此而崩溃。
因此,任何人请向我发送示例代码,以便我根据我的要求获得块。无论我需要哪一个,我只想得到那个。 请尽快回复。
I am trying to read a text file containing characters in billions. Using the functioncontentOfFile
is not working, as my application get crashed due to it.
So anybody please send me the sample code so that I get the chunks according to my requirement.Whichever i need i wanna get that one only.
please reply as soon as possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜这是一个 iOS 应用程序。在这种情况下,您可能会通过调用
contentsOfFile:
达到内存限制,因为该方法试图将文件的全部内容读入变量(内存)。请记住,在 iOS 上,您的应用程序必须运行良好,如果它决定消耗太多内存,那么看门狗进程将终止您的应用程序,以防止设备重新启动(发生这种情况是因为 iOS 设备上没有可交换的磁盘)。你看过
NSFileHandle
吗?NSFileHandle
支持在文本文件中查找。通过一些简单的迭代,您可以使用以下方法在文件中查找并读取数据块:它可能看起来像这样。假设
pathToFile
是一个NSString
,包含要读入的文本文件的路径。I'm guessing this is an iOS app. In that case, you are likely hitting the memory limit by calling
contentsOfFile:
because that method is trying to read the entire contents of the file into a variable (memory). Remember that on iOS your app must play nice and if it decides to consume too much memory, then the watchdog process will kill your app to save the device from rebooting (which happens because there is no disk to swap to on iOS devices).Have you had a look at
NSFileHandle
?NSFileHandle
supports seeking within a text a file. With some simple iteration you can use the following to methods to seek within the file and read chunks of data:It might look something like this. Assume
pathToFile
is anNSString
containing the path to the text file to be read in.一个好主意是查看 textedit 源代码,因为我之前用它打开过大量文件,应该有办法做到这一点。但不确定为什么你的应用程序崩溃了。应该没有问题。
A good idea is to look at the textedit source because I've opened massive files with it before and there should be a way to do it. Not sure why your app is crashing though. It shouldn't have a problem.