简体   繁体   中英

Ignore a line while reading a file in java

I have some code to read the lines from a file, I would like to recognize when the line starts or the fisrt character (not blank) is ' * ' and ignore it, so inside the while statement add something like

if(line[0]=='*') 
   ignore that line

I have something like:

   input = new BufferedReader(new FileReader(new File(finaName)));
    String line = null;
    while ((line = input.readLine()) != null) {
    String[] words = line.split(" "); 
        .... 
    }

How to complete the code?

input = new BufferedReader(new FileReader(new File(finaName)));
String line = null;
while ((line = input.readLine()) != null) {
  if(line.trim().indexOf('*') == 0)
    continue;
  String[] words = line.split(" "); 
    .... 
}

Change your while loop as:

while((line = input.readLine()) != null){
   if(!line.startsWith("*")){
      String[] words = line.split(" ");
      ....
   }
}

EDIT

If "*" is not in the beginning of the line but at some position in the line, use the following

if(line.indexOf("*") == position){
   ......
}

where position can be an integer specifying the position you are interested in.

Assuming the * marks and end of line comment, this loop will keep anything needed on the line before it.

    input = new BufferedReader(new FileReader(new File(finaName)));
    String line = null;
    char[] lineChars;
    while ((line = input.readLine()) != null) {
        lineChars = line.toCharArray();
        line = "";
        for(char c: lineChars){
            if(c == '*')break;
            line.concat(Character.toString(c));
        }
        if(!line.equals(""))
        String[] words = line.split(" ");           
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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