我如何解决这个java.lang.OutOfMemoryError:Java堆空间?

时间:2018-01-25 02:34:19

标签: java bufferedreader stringbuffer

我收到了java.lang.OutOfMemoryError:Java堆空间。我不确定我做错了什么。这是我的代码:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/jdk.internal.misc.Unsafe.allocateUninitializedArray(Unsafe.java:1250)
at java.base/java.lang.invoke.StringConcatFactory$MethodHandleInlineCopyStrategy.newArray(StringConcatFactory.java:1605)
at java.base/java.lang.invoke.DirectMethodHandle$Holder.invokeStatic(DirectMethodHandle$Holder)
at java.base/java.lang.invoke.LambdaForm$BMH/754666084.reinvoke(LambdaForm$BMH)
at java.base/java.lang.invoke.LambdaForm$MH/801197928.linkToTargetMethod(LambdaForm$MH)
at RunnerCombined.main(RunnerCombined.java:31)

collegeData 2.txt是44.2 mb,它是一个json文件。这是我的错误信息。

git log HEAD..origin/yourproject --graph

RunnerCombined.java:31是' addString + = nextLine'上方。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

谢谢twain249!将代码更改为此后,我的程序运行得很快,而且非常完美!

StringBuffer finalString = new StringBuffer();

    try {
        BufferedReader br = new BufferedReader(new FileReader("collegeData 2.txt"));
        StringBuffer returnFile = new StringBuffer();
        returnFile.append(br.readLine() + "\n" + br.readLine() + "\n");

        boolean completedFirstSection = false;
        int count = 2;
        StringBuffer addString = new StringBuffer();

        String nextLine;

        while ((nextLine=br.readLine())!=null) {
            if(count < 990) {
                addString.append(nextLine + "\n");
                count++;
            } else {
                String sub = nextLine.substring(16);
                sub = sub.substring(0, sub.length());

                // addString = sub + ":{" + nextLine + "," + addString.substring(0, addString.length()-2) + br.readLine();
                returnFile.append(sub + ":{" + nextLine + "," + "\n");
                returnFile.append(addString.substring(0, addString.length()-2) + "\n");
                returnFile.append(br.readLine() + "\n");
                addString.setLength(0);
                count = 2;
                br.readLine();
            }
        }
        returnFile.append("}}]");
        finalString = returnFile;
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }