2015-02-08 69 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