0

假设一个文件包含以下几行:

#Do
#not
#use
#these
#lines.

Use
these.

我的目标是只阅读那些不以#. 如何在 Java 中以最佳方式完成这项工作?

4

3 回答 3

2

让我们假设您想要累积行(当然您可以对每一行做任何事情)。

String filePath = "somePath\\lines.txt";

// Lines accumulator.
ArrayList<String> filteredLines = new ArrayList<String>();

BufferedReader bufferedReader = null;
try {
    bufferedReader = new BufferedReader(new FileReader(filePath));
    String line;

    while ((line = bufferedReader.readLine()) != null) {
        // Line filtering. Please note that empty lines
        // will match this criteria!
        if (!line.startsWith("#")) {
            filteredLines.add(line);
        }
    }
}
finally {
    if (bufferedReader != null)
        bufferedReader.close();
}

使用 Java 7 try-with-resources语句:

String filePath = "somePath\\lines.txt";
ArrayList<String> filteredLines = new ArrayList<String>();

try (Reader reader = new FileReader(filePath);
    BufferedReader bufferedReader = new BufferedReader(reader)) {

    String line;
    while ((line = bufferedReader.readLine()) != null) {
        if (!line.startsWith("#"))
            filteredLines.add(line);
    }
}
于 2012-10-29T20:02:05.740 回答
1

使用String.startsWith()方法。在你的情况下,你会使用 if(!myString.startsWith("#")) { //some code here }

于 2012-10-29T19:46:25.807 回答
0

BufferedReader.readLine() 返回一个字符串。您可以检查该行是否以#使用 string.startsWith()开头

FileReader reader = new FileReader("file1.txt");
    BufferedReader br  = new BufferedReader(reader);
    String line="";
    while((line=br.readLine())!=null){
        if(!line.startsWith("#")){
            System.out.println(line);
        }
    }
}
于 2012-10-29T19:47:13.730 回答