如何处理大字符串和有限的内存 [英] How to deal with big strings and limited memory
问题描述
我有一个文件,我从中读取数据。
此文件中的所有文本都存储在String变量(一个非常大的变量)中。
然后在我的应用程序的另一部分,我想要遍历此字符串并逐步提取有用的信息(解析字符串)。
I have a file from which I read data. All the text from this file is stored in a String variable (a very big variable). Then in another part of my app I want to walk through this string and extract useful information, step-by-step (parsing the string).
In同时我的记忆力已经满了,OutOfMemory异常使我无法进一步处理。
我认为在从文件中读取输入流时直接处理数据会更好。但是对于组织目标,我想将String传递给我的应用程序中的另一部分。
In the meanwhile my memory gets full and an OutOfMemory exception keeps me from further processing. I think it would be better to process the data directly while reading the inputstream from the file. But for organizational aims, I would like to pass the String to another part in my application.
我该怎么办才能防止内存溢出?
What should I do to keep the memory from overflowing?
推荐答案
如果您可以稍微放松一下您的要求,可以实施 java.lang.CharSequence 由您的文件支持。
If you can loosen your requirements a bit you could implement a java.lang.CharSequence backed by your file.
支持CharSequence JDK中的许多地方(字符串是CharSequence)。所以这是基于Reader的实现的一个很好的替代方案。
The CharSequence is supported many places in the JDK (A String is a CharSequence) . So this is a good alternative to a Reader-based implementation.
这篇关于如何处理大字符串和有限的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!