简体   繁体   English

Java条件读取文本文件

[英]Java Read Text file with condition

I'm just wondering if there's a way to read a text file and skip a line with specific string. 我只是想知道是否有一种方法来读取文本文件并跳过带有特定字符串的行。

For example (test1.txt): 例如(test1.txt):

test0,orig,valid,nice
test1,input,of,ol,[www]
test2,[eee],oa,oq
test3,wa,eee,string,int
test4,asfd,eee,[tsddas],wwww

Expected output : 预期产量:

test0,orig,valid,nice
test3,wa,eee,string,int

I already have this code : 我已经有了以下代码:

String line;
String test[];

try{
    LineIterator it = FileUtils.lineIterator(file2,"UTF-8");
    while(it.hasNext()){                    
        line = it.nextLine();                    
        test = StringUtils.split(line,(",")); 
    }

Thanks in advance guys! 在此先感谢大家!

Something like: 就像是:

line = it.nextLine();

if (line.contains("specific string")) continue;

test = StringUtils.split(line,(",")); 

Why are you using StringUtils to split a line? 为什么要使用StringUtils拆分行? The String class supports a split(...) method. String类支持split(...)方法。

I suggest you read the String API for basic functionality. 我建议您阅读String API的基本功能。

You could also make use of the Java 8 Streaming API. 您还可以使用Java 8 Streaming API。 It allows all this rather easily. 它使所有这一切变得很容易。

final List<String[]> rows = Files.lines(Paths.get(file2), "UTF-8")
        .filter(l -> !l.contains("["))
        .map(l -> l.split(","))
        .collect(Collectors.toList());

If you want to do it fast and don't want to run into any issues, you should also think about using an existing CSV library. 如果您想快速执行此操作并且不想遇到任何问题,则还应该考虑使用现有的CSV库。 A nice example is the Apache Commons CSV library ( https://commons.apache.org/proper/commons-csv/ ). 一个很好的例子是Apache Commons CSV库( https://commons.apache.org/proper/commons-csv/ )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM