如何检测Scanner收到的BlankLine?
我想获取数据表单文本文件,并使用Scanner获取数据表单文本文件。 它的配置文件保存模式
name status friend friend . . (Blank line)
空白行是每个配置文件分开的。(朋友将循环直到下一行是空行)
john happy james james sad john
我编写代码来获取这样的文件格式文本
try{ Scanner fileIn = new Scanner(new FileReader("testread.txt")); while(fileIn.hasNextLine()){ String line = fileIn.nextLine(); String linename = fileIn.nextLine(); String statusline = fileIn.nextLine(); println("name "+linename); println("status "+statusline); while(/*I asked at this*/)){ String friendName = fileIn.nextLine(); println("friend "+friendName); } } }catch(IOException e){ println("Can't open file"); }
我应该用什么条件来检测配置文件之间的空白行?
您可以实现如下所示的自定义函数,如果它不为空,它将返回nextLine
。
public static String skipEmptyLines(Scanner fileIn) { String line = ""; while (fileIn.hasNext()) { if (!(line = fileIn.nextLine()).isEmpty()) { return line; } } return null; }
您可以简单地检查您的scanner.nextLine()
是否为换行符"\n"
(我的意思是""
,因为nextLine()
在任何行的末尾都不读"\n"
)..如果它相等,它将是一个空行..
if (scanner.nextLine().equals("")) { /** Blank Line **/ }
顺便说一句,您的代码存在问题: –
while(fileIn.hasNextLine()){ String line = fileIn.nextLine(); String linename = fileIn.nextLine(); String statusline = fileIn.nextLine();
您假设您的fileIn.hasNextLine()
将确认接下来的三行not null
。
每次你做一个fileIn.nextLine()
你需要检查它是否可用..或者你会得到例外……
* 编辑: – Oo ..我看到你已经处理了exception..然后就没有问题..但是你仍然应该修改上面的代码..它看起来不漂亮..
使用scanner.hasNextLine()
方法检查现有行后,您可以使用以下条件:
String line = null; if((line = scanner.nextLine()).isEmpty()){ //your logic when meeting an empty line }
并在逻辑中使用line
变量。
尝试这个…
while(scanner.hasNextLine()){ if(scanner.nextLine().equals("")){ // end of profile one... } }