当输入文件中出现错误时,是否可以找出扫描仪在输入文件的哪一行失败?
以下代码始终打印出阅读器中的总行数,而不是发生错误的行号:
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.junit.Test;
public class ScannerTests {
static private final String text = "FUNCTION_BLOCK Unnamed_project\n\tVAR_INPUT\n\t\tUnnamed_variable1::REAL;\n\tEND_VAR\nEND_FUNCTION_BLOCK";
@Test
public void scannerLineNumberFailedTest() {
LineNumberReader reader = new LineNumberReader(new StringReader(text));
int lineNumber = -1;
try {
Scanner sc = new Scanner(reader);
sc.useDelimiter("\\s*\\b\\s*");
sc.next("(?i)FUNCTION_BLOCK");
String blockName = sc.next();
assert sc.hasNext("(?i)VAR_INPUT");
sc.next("(?i)VAR_INPUT");
String variableName = sc.next();
sc.next(":"); // line of failure - got a unexpected '::'
String type = sc.next("\\w+");
sc.next(";");
sc.next("(?i)END_VAR");
sc.next("(?i)END_FUNCTION_BLOCK");
assert "Unnamed_project".equals(blockName);
assert "Unnamed_variable1".equals(variableName);
assert "REAL".equals(type);
sc.close();
} catch (NoSuchElementException ex) {
lineNumber = reader.getLineNumber() + 1;
System.err.println("Error in line: " + lineNumber);
}
assert lineNumber == 3;
}
}