Exception in thread "main" java.lang.OutOfMemoryError: Java heap space if i'm scann many folder

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space if i'm scann many folder

我正在尝试对包含单词存根的项目执行扫描,以便在其中搜索文件。 UTF-16 编码的文件。但是,当解析器处理到 1017 个文件时,都出现错误:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space.

我该如何解决?

import java.io.*;
import java.util.Scanner;

public class FolderScanerV2 {

    public static void FolderScaner(File file) throws Exception {
        if (file.isDirectory()) {
            File[] directory = file.listFiles();
            for (File enter : directory) {
                if ((enter.isFile() & enter.getCanonicalPath().contains("txt"))) {
                    FileScaner(enter);
                } else {
                    FolderScaner(enter);
                }
            }
        }
    }

    public static void FileScaner(File file) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF-16"));
        Scanner text = new Scanner(in);
        while (text.hasNext()) {
            if(text.next().contains("Cap")) {
                System.out.println("Cap" + " " + file.getCanonicalPath());
            }
        }
        text.close();
        in.close();
    }

    public static void main(String[] args) {
        String path = new String();
        Scanner inpunt = new Scanner(System.in);
        System.out.println("Input path");
        path = inpunt.nextLine(); // 

        File dir = new File(path);
        path.close();
        try {
            FolderScaner(dir);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

您需要为 jvm 提供更多内存。您可以在下面的 post 中找到该过程。

Increase heap size in Java

感谢您添加 VM 选项:-Xms512m -Xmx1024m -XX:-UseGCOverheadLimit 和所有作品