[英]how can i use the trim() method to make this work? I need to read the txt file while ignoring the blank line and lines that start with "//"
public void readToooooolData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
scanner.useDelimiter("( *, *)|(\\s*,\\s*)|(\r\n)|(\n)");
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!line.startsWith("//") || !(scanner.nextLine().startsWith(" ") )) {
String toolName = scanner.next();
String itemCode = scanner.next();
int timesBorrowed = scanner.nextInt();
boolean onLoan = scanner.nextBoolean();
int cost = scanner.nextInt();
int weight = scanner.nextInt();
storeTool( new Tool(toolName, itemCode, timesBorrowed, onLoan, cost, weight) );
scanner.nextLine();
}
scanner.close();
}
}
txt文件:
// this is a comment, any lines that start with //
// (and blank lines) should be ignored
// data is toolName, toolCode, timesBorrowed, onLoan, cost, weight
Makita BHP452RFWX,RD2001, 12 ,false,14995,1800
Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200
DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400
Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000
Bosch GSR10.8-Li Drill Driver,RD3021,25, true,9995,820
Bosch GSB19-2REA Percussion Drill,RD8654,85,false,19999,4567
Flex Impact Screwdriver FIS439, RD2835,14,false,13499,1200
DeWalt DW936 Circular Saw,RD4352,18,false,19999,3300
Sparky FK652 Wall Chaser,RD7625,15,false,29994,8400
您的代碼存在一些問題。
最好使用try with resources來打開 Scanner
您指定的一些分隔符是重復的,有些是不必要的。 \s
中包含空格,因此(\s*,\s*)
是( *, *)
的副本,並且(\r\n)|(\n)
不是必需的。
您從文件中讀取一行並測試是注釋行還是空行 - 好的。 然后你需要從已經閱讀的行中提取標記,但是你不能為此使用scanner.next()
,因為它會在你剛剛閱讀的行之后檢索你的下一個標記。 因此,您的代碼實際上正在做的是嘗試解析非注釋/非空行之后的行中的信息。
在循環的末尾還有另一個scanner.nextLine()
,因此您可以從文件中再跳過一行。
public void readToooooolData(String fileName) throws FileNotFoundException {
File dataFile = new File(fileName);
try (Scanner scanner = new Scanner(dataFile)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (line.startsWith("//") || line.isEmpty()) {
continue;
}
String tokens[] = line.split("\\s*,\\s*");
if (tokens.length != 6) {
throw new RuntimeException("Wrong data file format");
}
String toolName = tokens[0];
String itemCode = tokens[1];
int timesBorrowed = Integer.parseInt(tokens[2]);
boolean onLoan = Boolean.parseBoolean(tokens[3]);
int cost = Integer.parseInt(tokens[4]);
int weight = Integer.parseInt(tokens[5]);
storeTool( new Tool(toolName, itemCode, timesBorrowed, onLoan, cost, weight) );
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.