Roberto
Roberto

Reputation: 997

Java Scanner skip a row of dashes

I have a file that has two columns, one for full names (first name and last name) and one for ID numbers. The file also has a header with "Name" and "ID", and right below the header and above all the entries, there is a a line of dashes separated by spaces. It looks like this:

NAME        ID
------      ------
John Snow   0001
Tyrion      0002

I want to be able to skip this row of dashes and I've been trying to use Scanner.skip() with no avail. I already set up within a while loop a regex to split the spaces between columns and an if statement to bypass the column headers.

Upvotes: 1

Views: 1215

Answers (4)

Arnab Datta
Arnab Datta

Reputation: 5256

If you are already using Scanner, then try this :

String curLine;

while (scan.hasNext()){
    curLine = scan.readLine();
    if(!curLine.startsWith("----") {
        .... //whatever code you have for lines that don't contain the dashes

    }
}

Upvotes: 0

Guillaume Polet
Guillaume Polet

Reputation: 47607

You could proably use a BufferedReaderinstead of a Scanner. It has a readLine() method that could be used then to skip those dashes.

BufferedReader reader = new BufferedReader(... your input here...);
String s;
while((s=reader.readLine())!=null) {
   if (s.startWith("--")
       continue;
   // do some stuffs

}

EDIT: If you want to be sure that the lines contains only dashes and spaces you could use:

s.matches("[\\- ]+")

which will match only if your line contains dashes and blanks

Upvotes: 1

Srinivas M.V.
Srinivas M.V.

Reputation: 6608

FileReader fileReader = new FileReader(//File with Exension);

Scanner fileScan = new Scanner(fileReader);

fileScan.useDelimiter("\\-")

while(fileScan.hasNext()){

   //Store the contents without '-'
   fileScan.next();
}

Hope this helps

Upvotes: 0

sgowd
sgowd

Reputation: 2262

If the first two lines are always static, try this-

reader.readLine(); //reads first line, Name ID and does nothing
reader.readLine(); //reads second line, ---- ---- and does nothing
//start scanning the data from now.
while(!EOF){
String line = reader.readLine();
//process the data.
}

In this way you can eliminate overhead of comparing each and every line with "--".

Upvotes: 0

Related Questions