正在读取文件 java.lang.OutOfMemoryError

reading file java.lang.OutOfMemoryError

正在尝试在大型文件中查找单词。逐行读取文件。读取时抛出 redLine 异常的方式。有什么办法解决这个问题吗?您可以在地板上以字符串形式阅读它吗?

for(String line; (line = fileOut.readLine()) != null; ){
                    if(line.contains(commandString)) 
                        System.out.println(count + ": " + line);
                    count++;
                }

java.lang.OutOfMemoryError:

UDP:

这是我所有的错误代码:

static String file = "files.txt";
    static String commandString = "first";
    static int count = 1;

    public static void main(String[] args) throws IOException 
    {

        try(BufferedReader fileOut = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1251")) ){


            for(String line; (line = fileOut.readLine()) != null; ){
                    if(line.contains(commandString)) 
                        System.out.println(count + ": " + line);
                    count++;
                }





            System.out.println("before wr close :"  + Runtime.getRuntime().freeMemory());
            fileOut.close();

        }catch(Exception e) {
            System.out.println(e);
        }
    }

搜索一个词,您可以按字节读取文件,而不会在内存中保留超过一个字节的文件。 逐字节读取,每次一个字节等于搜索字的第一个字节,开始第二个循环并读取以下字节并检查下一个字节是否等于字中的下一个字节等。 给你举个例子,我已经根据你的需要修改了一个样本。
我省略了文件的输出,因为我不知道,如果你想输出所有行或只输出包含你的关键字的行,而后者可能与逐行阅读代码一样有问题。

static String fileName = "files.txt";
static byte[] searchString = { 'f', 'i', 'r', 's', 't' };
static int count = 0;
static long position = 1;
public static void main(String[] args) throws IOException {

    try (FileInputStream file = new FileInputStream(fileName)) {
        byte read[] = new byte[1];
        outerLoop: while (-1 < file.read(read, 0, 1)) {
            position++;
            if (read[0] == searchString[0]) {
                int matches = 1;
                for (int i = 1; i < searchString.length; i++) {
                    if (-1 > file.read(read, 0, 1)) {
                        break outerLoop;
                    }
                    position++;
                    if (read[0] == searchString[i]) {
                        matches++;
                    } else {
                        break;
                    }
                }
                if (matches == searchString.length) {
                    System.out.println((++count)+". found at position "+ (position-matches));
                }
            }

        }
        file.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}