读取文件java.lang.OutOfMemoryError

时间:2015-02-08 20:26:05

标签: java arrays string out-of-memory

尝试在大文件中查找单词。文件逐行读取。读取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);
        }
    }

1 个答案:

答案 0 :(得分:1)

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

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();
    }
}