2012-04-04 79 views
13

我目前正在學習Java,並且遇到了這個問題,我想加載一個包含大量行的文件(我正在逐行讀取文件),而我想要做的事情是跳過某些行(僞-碼)。如何從java中的文本文件跳過某些行?

the line thats starts with (specific word such as "ABC") 

我曾嘗試使用

if(line.startwith("abc")) 

但沒有奏效。我不知道如果我做錯了,這就是爲什麼我在這裏尋求幫助,下面的負載功能的一部分:

public String loadfile(.........){ 

//here goes the variables 

try { 

     File data= new File(dataFile); 
     if (data.exists()) { 
      br = new BufferedReader(new FileReader(dataFile)); 
      while ((thisLine = br.readLine()) != null) {       
       if (thisLine.length() > 0) { 
        tmpLine = thisLine.toString(); 
        tmpLine2 = tmpLine.split(......); 
        [...] 
+0

+1。不知道爲什麼這被拒絕,但回到0. – Neil 2012-04-04 09:04:44

+0

-1與java-ee servlets或jsp無關以及已被刪除的帖子的副本 – 2012-04-04 09:04:48

+2

+1不確定是否投棄權票。如果有錯誤的標籤,只需糾正它們... – devsnd 2012-04-04 09:05:31

回答

9

嘗試

if (line.toUpperCase().startsWith(­"ABC")){ 
    //skip line 
} else { 
    //do something 
} 

這將line全部轉換爲通過使用功能toUpperCase()上字符並將檢查字符串是否以ABC開頭。

如果它是true那麼它什麼都不做(跳過線)並進入else部分。

您還可以使用startsWithIgnoreCase,這是Apache Commons提供的功能。它需要兩個字符串參數。

public static boolean startsWithIgnoreCase(String str, 
              String prefix) 

此函數返回布爾值。 並檢查一個字符串是否以指定的前綴開頭。

如果字符串以前綴開頭,則它返回true,不區分大小寫。

+0

這。不知道他是否給了我們快速的psuedocode,或者實際上他在做什麼,但是'startwith'和'startsWith'不一樣,'abc'和ABC不一樣 – Nicholas 2012-04-04 14:37:05

2

如果情況是不使用的重要嘗試StringUtils.startsWithIgnoreCase(String str, String prefix)Apache Commons

This function return boolean. 

See javadoc here

用法:

if (StringUtils.startsWithIgnoreCase(­line, "abc")){ 
    //skip line 
} else { 
    //do something 
} 
+0

看起來像'one -liner'由vikiii發佈。 – 2012-04-04 09:18:20

+1

非常真實。 我認爲新手Java程序員儘快學習Apache Commons庫非常重要,所以他們不會重寫常用實用程序。 – 2012-04-04 09:20:54

+0

在完成了幾次之後,我現在看到了你的觀點。 – 2012-04-04 09:27:51

1

如果你有一個大的輸入文件,你的代碼將創建一個OutOfMemoryError。如果沒有編輯代碼,就無法對付它(如果文件變大,添加更多內存將失敗)。

我說你把選定的行存儲在內存中。如果文件變大(2GB左右),則內存容量將達到4GB。 (String的舊值和新值)。

你必須使用流來解決這個問題。

創建一個FileOutpuStream,並將選定的行寫入該流中。

您的方法必須更改。對於較大的輸入喲不能返回一個字符串:

public String loadfile(...){ 

您可以返回Stream或文件。

public MyDeletingLineBufferedReader loadFile(...) 
0

你可以使用:

BufferedReader br = new BufferedReader(new FileReader("file.txt")); 
    String lineString; 
    try{ 
    while((lineString = br.readLine()) != null) { 
     if (lineString.toUpperCase().startsWith(­"abc")){ 
      //skip 
      } else { 
      //do something 
      } 
     } 
    } 

static boolean startsWithIgnoreCase(String str, String prefix)方法org.apache.commons.lang.StringUtils像下面。

BufferedReader br = new BufferedReader(new FileReader("file.txt")); 
     String lineString; 
     try{ 
      while((lineString = br.readLine()) != null) { 
       if (StringUtils.startsWithIgnoreCase(­lineString, "abc")){ 
       //skip 
       } else { 
       //do something 
       } 
       } 
      } 
相關問題