文本文件读取
本文提供了阅读文本文件的技巧。但我想首先阅读整个文件。然后我想通过new String(bytes, "UTF-8")
创建一个字符串。但我需要大量的内存来执行此操作。如何进行字节转换为字符串和字节释放的并行过程。我的意思是,当一个新的字符串符号出现在内存中时,这些字节就会被释放。
This article has tips on reading text files. But I want firstly to read the whole file. Then I want to create a string through new String(bytes, "UTF-8")
. But I need a big amount of memory for this operations. How to make a parallel process of the bytes translation to string and the bytes release. I mean when a new string symbol appear in memory from bytes this bytes are released.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行多个调用 read FileInputStream 中的方法,每次调用时读取所需的字节数:
为读取的 len 字节块创建一个新字符串。
然后连接字符串。
无论如何,这不会帮助节省太多内存。
perform multiple call of read method in FileInputStream with the desired amount of byte to be read for each call:
The create a new string for chunk of len bytes read.
Then concatenate the string.
Anyway this won't help to save much memory.
您无法一次有效地构建一个字符串。
我认为你能做的最好的事情是这样的:
只要你对文件大小的估计是好的(并且不小于实际大小!),这不会使用比绝对必要的更多的空间。问题是操作系统报告的文件大小将以字节为单位而不是以字符为单位,并且对于 UTF-8 等编码方案,这两个大小之间没有简单的关系。
You can't efficiently build a String a bit at a time.
I think that the best that you can do is something like this:
Provided that your estimate of the file size is good (and not less that the actual size!), this won't use much more space than is absolutely necessary. The problem is that the file size reported by the OS will be the size in bytes not in characters, and there's no simple relationship between the two sizes for an encoding scheme like UTF-8.