Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip certain line from Text file in java?

I am currently learning Java and I have faced this problem where I want to load a file that consists a huge number of lines (I am reading the file line by line ) and the thing I want to do is skip certain lines (pseudo-code).

the line thats starts with (specific word such as "ABC")

I have tried to use

if(line.startwith("abc"))

But that didn't work. I am not sure if I am doing it wrong, that's why I am here asking for a help, below part of the load function:

public String loadfile(.........){

//here goes the variables 

try {

        File data= new File(dataFile);
        if (data.exists()) {
            br = new BufferedReader(new FileReader(dataFile));
            while ((thisLine = br.readLine()) != null) {                        
                if (thisLine.length() > 0) {
                    tmpLine = thisLine.toString();
                    tmpLine2 = tmpLine.split(......);
                    [...]
like image 788
Serag Alzetnani Avatar asked Apr 04 '12 09:04

Serag Alzetnani


2 Answers

Try

if (line.toUpperCase().startsWith(­"ABC")){
    //skip line
} else {
    //do something
}

This will converts the line to all the Upper Characters by using function toUpperCase() and will check whether the string starts with ABC .

And if it is true then it will do nothing(skip the line) and go into the else part.

You can also use startsWithIgnoreCase which is a function provided by the Apache Commons . It takes the two string arguments.

public static boolean startsWithIgnoreCase(String str,
                                           String prefix)

This function return boolean. And checks whether a String starts with a specified prefix.

It return true if the String starts with the prefix , case insensitive.

like image 155
vikiiii Avatar answered Sep 22 '22 12:09

vikiiii


If the case isn't important try using the StringUtils.startsWithIgnoreCase(String str, String prefix) of Apache Commons

This function return boolean.

See javadoc here

Usage:

if (StringUtils.startsWithIgnoreCase(­line, "abc")){
    //skip line
} else {
    //do something
}
like image 44
Boosty Avatar answered Sep 20 '22 12:09

Boosty