2015-02-08 65 views
0

试图在大文件中查找单词。文件逐行读取。读取redLine异常的方式时抛出。有没有办法解决这个问题?你可以在地板上看到它作为一个字符串?读取文件java.lang.OutOfMemoryError

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

这不应该是'for'循环。但无论如何,'fileOut'是什么,它是如何定义和打开的?该文件来自哪里,你确定它被正确地分解成行而不是数据/二进制文件? – RealSkeptic 2015-02-08 20:32:57

+1

您应该向我们展示堆栈跟踪以及与发生错误的行相关的支持代码。您提供的循环显示行字段被重复覆盖,这不会导致OOM。 – MarsAtomic 2015-02-08 20:33:26

+1

为什么在找到commandString时不打破for循环? – 2015-02-08 20:37:12

回答

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

感谢您的回答! – asdascascaedfa 2015-02-09 22:23:53