Problem with Scanner... Help!
Hi... experts, I'm trying to use java.util.Scanner to read a file. I have a few lines of comments in the file like follows:
################
# configuration file #
################
# comment 1
# comment 2
the comments all start with "#", I'm trying to skip these comment lines, and I used
Scanner s =new Scanner(file).skip("#.*");
to solve the problem, but it just skipped the first line, which is "###########", and it still read the second line "# configuration file #". Can any one help me solve this problem? Thanks a lot...
Regards,
Yating
Only the first part of the scanner is being skipped (until the line-break).
Try something like this:
Scanner scan = new Scanner(file);
while(scan.hasNextLine()) {
String line = scan.nextLine();
if(!line.matches("#.*")) {
System.out.println(line);
}
}
prometheuzz, thank you very much for such a quick reply. It works fine! And based on that I'm trying to read the rest of the file, like:
a = FFFFFFFF
b = EEEEEEEE
c = DDDDDDDD
d = CCCCCCCC
as expected such "FFFFFFFF", "EEEEEEEE" will be read into the program. Based on your code, I added a bit more:
Scanner scan = new Scanner(file);
while(scan.hasNextLine()) {
String line = scan.nextLine();
if(!line.matches("#.*")) {
scan.useDelimiter("\\w*\\s*=\\s*");
System.out.println(scan.next());
}
}
The expected result is:
FFFFFFFF
EEEEEEEE
DDDDDDDD
CCCCCCCC
but the actual result is like:
EEEEEEEE
CCCCCCCC
could you please tell me why? Thanks a lot!!!
Yating