2015-06-04 68 views
0

我真的很喜歡這個。我想知道在閱讀文件時是否可以從arraylist中排除所有元素?先謝謝你!Java ArrayList和FileReader

我有這樣對我的ArrayList(excludelist)元素:像這樣

test1 
test2 
test3 

而且我有我的文件CSV數據(readtest):

test1,off 
test2,on 
test3,off 
test4,on 

所以我很期待是排除在while循環中arraylist的所有數據然後將如下輸出:

test4,on

這是我的代碼:

String exclude = "C:\\pathtomyexcludefile\\exclude.txt";  
String read = "C:\\pathtomytextfile\\test.txt"; 

        File readtest = new File(read); 
        File excludetest = new File(exclude); 

        ArrayList<String> excludelist = new ArrayList(); 
        excludelist.addAll(getFile(excludetest)); 

    try{ 
      String line; 
        LineIterator it = FileUtils.lineIterator(readtest,"UTF-8"); 
        while(it.hasNext()){ 
      line = it.nextLine(); 
      //determine here 

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

    public static ArrayList<String> getFile(File file) { 
      ArrayList<String> data = new ArrayList(); 
      String line; 
       try{ 
       LineIterator it = FileUtils.lineIterator(file,"UTF-8"); 
        while(it.hasNext()){ 
         line = it.nextLine(); 
         data.add(line);  
       } 
        it.close(); 
       } 

          catch(Exception e){ 
       e.printStackTrace(); 
       } 
      return data; 
     } 
+0

你有什麼問題?到目前爲止,你已經做了什麼調試? –

回答

0

如果排除元素是AA String對象,你可以嘗試這樣的事:

while(it.hasNext()){ 
    line = it.nextLine(); 
    for(String excluded : excludelist){ 
     if(line.startsWith(excluded)){ 
      continue; 
     } 
    } 
} 
1

可能有更有效的方式來做到這一點,但是您可以使用String.startsWith針對excludeList中的每個元素檢查您正在閱讀的每一行。如果該行不是以要排除的單詞開始,請將其添加到approvedLines列表中。

String exclude = "C:\\pathtomyexcludefile\\exclude.txt";  
String read = "C:\\pathtomytextfile\\test.txt"; 

File readtest = new File(read); 
File excludetest = new File(exclude); 

List<String> excludelist = new ArrayList<>(); 
excludelist.addAll(getFile(excludetest)); 
List<String> approvedLines = new ArrayList<>(); 

LineIterator it = FileUtils.lineIterator(readtest, "UTF-8"); 

while (it.hasNext()) { 
    String line = it.nextLine(); 
    boolean lineIsValid = true; 
    for (String excludedWord : excludelist) { 
     if (line.startsWith(excludedWord)) { 
      lineIsValid = false; 
      break; 
     } 
    } 
    if (lineIsValid) { 
     approvedLines.add(line); 
    } 
} 

// check that we got it right 
for (String line : approvedLines) { 
    System.out.println(line); 
} 
+0

我不能做這個,我不能把這條線放在記憶裏。我正在閱讀大文件文本。 – tuturyokgaming