java - 尝试使用 UTF-8 编码 Files.write(..) 但出现 OutOfMemoryError

标签 java utf-8 out-of-memory

我正在尝试使用 UTF-8 对我的文本文件进行编码。当我这样做时,它起作用了。

protected void writeFile(Path dir, StringBuilder sb) {
    try {
        String fileName = dir.toFile().getAbsolutePath() + File.separator + getClass().getSimpleName().toLowerCase() + ".impex";
        Path path = Paths.get(fileName);
        Files.write(path, sb.toString().getBytes(), StandardOpenOption.CREATE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

但是当我使用 UTF-8 或 UTF8 编码时,我得到了 java.lang.OutOfMemoryError: Java heap space。为什么会这样,我该如何解决这个问题? (我的内存设置已经是2GB了)

protected void writeFile(Path dir, StringBuilder sb) {
    try {
        String fileName = dir.toFile().getAbsolutePath() + File.separator + getClass().getSimpleName().toLowerCase() + ".impex";
        Path path = Paths.get(fileName);
        Files.write(path, sb.toString().getBytes("UTF8"), StandardOpenOption.CREATE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

最佳答案

查看 getBytes 的实现,我发现

    byte[] encode(char[] ca, int off, int len) {
        int en = scale(len, ce.maxBytesPerChar());
        byte[] ba = new byte[en];

int en = scale(len, ce.maxBytesPerChar()); 请求的字节大小大约是 String 的 4 倍。

调试您的代码并确定它何时会出现 OutOfMemory

关于java - 尝试使用 UTF-8 编码 Files.write(..) 但出现 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019575/

相关文章:

JavaFx 希腊字符编码

ruby - 如何在 Ruby 2.1 中获取给定 UTF-8 代码的字符

c# - 限制同时发出的 Web 服务请求数

Java - 字符串按每个字符拆分

java - 如何在文本文件中简单地写入和读取整数数据?

string - 将未转义的 unicode 转换为 utf8 整数

java - 如何通过J2ME存储大图像

java - 此程序中针对 int 数组的错误在两种不同情况下表现不同

java - 扫雷地雷不会放置或出现

java - Guava Maps.Scala map 上的差异