0

Suppose a file contains the following lines:

#Do
#not
#use
#these
#lines.

Use
these.

My aim is to read only those lines which does not start with #. How this can be optimally done in Java?

  • 1
    What have you tried? Have you read the [documentation of the String class](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html)? – JB Nizet Oct 29 '12 at 19:46

3 Answers3

2

Let's assume that you want to accumulate the lines (of course you can do everything with each line).

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();
}

Using Java 7 try-with-resources statement:

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);
    }
}
1

Use the String.startsWith() method. in your case you would use if(!myString.startsWith("#")) { //some code here }

swabs
  • 515
  • 1
  • 5
  • 19
0

BufferedReader.readLine() return a String. you could check if that line starts with # using 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);
        }
    }
}
PermGenError
  • 45,977
  • 8
  • 87
  • 106