文本文件读取

发布于 2024-12-06 01:54:28 字数 271 浏览 0 评论 0原文

本文提供了阅读文本文件的技巧。但我想首先阅读整个文件。然后我想通过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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拥有 2024-12-13 01:54:28

执行多个调用 read FileInputStream 中的方法,每次调用时读取所需的字节数:

public int read(byte[] b,
                int off,
                int len)

为读取的 len 字节块创建一个新字符串。
然后连接字符串。

无论如何,这不会帮助节省太多内存。

perform multiple call of read method in FileInputStream with the desired amount of byte to be read for each call:

public int read(byte[] b,
                int off,
                int len)

The create a new string for chunk of len bytes read.
Then concatenate the string.

Anyway this won't help to save much memory.

宛菡 2024-12-13 01:54:28

您无法一次有效地构建一个字符串。

我认为你能做的最好的事情是这样的:

    String str = null;
    BufferedReader r = new BufferedReader(new FileReader("filename", "UTF-8"));
    try {
        StringBuilder sb =
             new StringBuilder(/* approx size of file in CHARACTERS */);
        int ch;
        while ((ch = r.read()) != -1) {
            sb.append((char) ch);
        }
        str = sb.toString();
    } finally {
        r.close();
    }

只要你对文件大小的估计是好的(并且不小于实际大小!),这不会使用比绝对必要的更多的空间。问题是操作系统报告的文件大小将以字节为单位而不是以字符为单位,并且对于 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:

    String str = null;
    BufferedReader r = new BufferedReader(new FileReader("filename", "UTF-8"));
    try {
        StringBuilder sb =
             new StringBuilder(/* approx size of file in CHARACTERS */);
        int ch;
        while ((ch = r.read()) != -1) {
            sb.append((char) ch);
        }
        str = sb.toString();
    } finally {
        r.close();
    }

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文