我正在尝试使用 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/