2012-04-20 32 views
1

我有一个文件,有两列,一个用于全名(名和姓),另一个用于ID号。该文件还有一个带有“名称”和“ID”的标题,在标题的正下方以及所有条目的上方,有一行用空格分隔的破折号。它看起来像这样:Java扫描器跳过一行破折号

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

我希望能够跳过此行破折号,我一直在尝试使用Scanner.skip()与无济于事。我已经在while循环中设置了一个正则表达式来分隔列之间的空格和if语句来绕过列标题。

回答

1

您可以合理使用BufferedReader而不是扫描仪。它有一个readLine()方法,可以用来跳过这些破折号。

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

} 

编辑: 如果你想确保该行只包含短划线和空格,你可以使用:

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

如果你的行包含破折号和空格

+0

我同一个解决方案。我会检查,如果行只包含无用的字符,所以我一定不会放弃一些数据,例如“--Doe”,例如..但是BufferedReader对我来说也更好:) – MykoB 2012-04-20 09:47:52

+0

@ guillaume-polet,什么是BufferedReader的原因似乎比Scanner更好? – 2012-04-20 12:24:05

+0

我也想知道。我将在稍后尝试,因为我没有使用skip()或useDelimiter()获取任何内容。它不断阅读虚线。 – Roberto 2012-04-20 16:27:32

0

将只匹配如果前两行始终是静态的,请尝试此操作 -

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. 
} 

在th是你可以消除比较每一行与“ - ”的开销。

+0

这就是我现在所做的。它有效,但我觉得它有点“肮脏”,哈哈。 – Roberto 2012-04-20 15:35:14

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

Scanner fileScan = new Scanner(fileReader); 

fileScan.useDelimiter("\\-") 

while(fileScan.hasNext()){ 

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

希望如果你已经在使用扫描仪这有助于

+0

我没有得到任何与skip()或useDelimiter()。它不断阅读虚线。我用“\\ - ”和“[\\ - ] +”无济于事。 – Roberto 2012-04-20 16:29:53

0

,那就试试这个:

String curLine; 

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

    } 
}