2016-04-26 34 views
2

我有一個Java method(下圖)來檢查一個text filestring值然後加上然後到list確保文本文件中的空行沒有添加到列表中?

public List<String> iterateTextFile(String filePath) { 

     List<String> lines = new ArrayList<String>(); 
     try { 
      lines = Files.readLines(new File(filePath), Charset.forName("utf-8")); 
     }catch(IOException e){ 
      e.printStackTrace(); 
     } 
     return lines; 
    } 

然而,這種方法將增加空行例如爲:""ArrayList爲好。我不想要這個?

如何添加驗證以使其不會發生?

回答

0

之前返回刪除空元素是: -

for(int i =0; i < lines.size(); i++) { 
    if(list.get(i).equals("")) { 
    list.remove(i); 
    } 
} 
return list; 
0

它們進行過濾:

public List<String> iterateTextFile(String filePath) { 

     List<String> lines = new ArrayList<String>(); 
     try { 
      lines = Files.readAllLines(Paths.get(filePath)).stream().filter(str -> !str.trim().isEmpty()).collect(Collectors.toList()); 
     }catch(IOException e){ 
      e.printStackTrace(); 
     } 
     return lines; 
    } 

換流前的Java版本,你可以做這樣的(你上一個位置去0,所以您不必筆芯):

public List<String> iterateTextFile(String filePath) { 

     List<String> lines = new ArrayList<String>(); 
     try { 
      lines = Files.readLines(new File(filePath), Charset.forName("utf-8")); 
      eliminateEmptyStrings(list); 
     }catch(IOException e){ 
      e.printStackTrace(); 
     } 
     return lines; 
    } 

    private void eliminateEmptyStrings(List<String> strings) { 
    for (int i = strings.size() - 1; i >= 0; i--) { 
     if (strings.get(i).trim().isEmpty()) strings.remove(i); 
    } 
} 

注意:添加聲明以檢查是否存在空值,或者您最終可能會收到一些NPE或其他不受控制的異常。

0

這個答案看看:只要修改「LineProcessor」過濾掉空行!

link

0

您也可以嘗試像

List<String> lines = new LinkedList<>(); 
int lineCounter = 0; 
Scanner scanner = new Scanner(new File(filePath)); 
while(scanner.hasNext()){ 
    String currentLine = scanner.nextLine(); 
    lineCounter++; 
    if(currentLine!=null && currentLine.length()==0){ 
     System.out.println("Skipping empty line number:" + lineCounter); 
    }else{ 
     lines.add(currentLine); 
    } 

} 

看到,使用計數器變量來表示,如果這個工作正常與否。那麼,這個代碼顯然帶有FileNotFoundException需要照顧。

相關問題