java扫描仪如何读取所有内容?
How to read all content by java Scanner?
此代码错误:
String result = "";
while (scanner.hasNextLine()) {
result += scanner.nextLine() + System.lineSeparator();
}
System.out.println(result);
因为nextLine()
无法区分行分隔符或EOF(没有空行).
那么扫描仪如何准确读取所有内容呢?
你不能。扫描仪不是完成这项工作的正确工具。你有一些意见。然后,您将该输入包装在扫描仪中。那是你的错误。
如果你不这样做,这个练习(将其全部读入一个巨大的字符串)将是微不足道的。
我们可以将扫描仪屠杀得面目全非,让它做一些原本设计不做的事情:
String example = "a\nb\r\nc\r\n";
scanner.useDelimiter("Well, this string certainly isn't in there!");
String result = scanner.next();
System.out.println(example.equals(result));
true
不过,不确定您要用它完成什么。 Scanner 意味着 'I want the exact line ending the original input had' 之类的东西不再重要了。如果他们这样做,请不要使用扫描仪。
此代码错误:
String result = "";
while (scanner.hasNextLine()) {
result += scanner.nextLine() + System.lineSeparator();
}
System.out.println(result);
因为nextLine()
无法区分行分隔符或EOF(没有空行).
那么扫描仪如何准确读取所有内容呢?
你不能。扫描仪不是完成这项工作的正确工具。你有一些意见。然后,您将该输入包装在扫描仪中。那是你的错误。
如果你不这样做,这个练习(将其全部读入一个巨大的字符串)将是微不足道的。
我们可以将扫描仪屠杀得面目全非,让它做一些原本设计不做的事情:
String example = "a\nb\r\nc\r\n";
scanner.useDelimiter("Well, this string certainly isn't in there!");
String result = scanner.next();
System.out.println(example.equals(result));
true
不过,不确定您要用它完成什么。 Scanner 意味着 'I want the exact line ending the original input had' 之类的东西不再重要了。如果他们这样做,请不要使用扫描仪。