简体   繁体   English

读取文件时忽略新行

[英]Ignore new lines while reading a file

I'm trying to read text inside a .txt document using console command java program < doc.txt . 我正在尝试使用控制台命令java program < doc.txt读取.txt文档中的文本。 The program should look for words inside a file, and the file CAN contain empty new lines, so I've tried changing the while condition from: 程序应查找文件中的单词,文件CAN包含空的新行,所以我尝试更改while条件:

while((s = in.nextLine()) != null)

to: 至:

while((s = in.nextLine()) != "-1")

making it stop when it would have found -1 (I've also tried with .equals() ), but it does not work. 它会在找到-1时停止(我也尝试过.equals() ),但它不起作用。 How can I tell my program to stop searching for words when there's no more text to examine? 当没有更多要检查的文本时,如何告诉我的程序停止搜索单词? Otherwise it keeps stopping when it finds an empty string (newline alone or sequence of new lines). 否则它会在找到空字符串时单独停止(单独的换行符或新行的序列)。

I've only found solutions using BufferedReader , but I don't know how to use it in this situation where the file is being read by the console command java program < doc.txt . 我只找到使用BufferedReader解决方案,但我不知道如何在控制台命令java program < doc.txt读取文件的情况下使用它。

I post the code inside the while, if it can be necessary: 如果有必要,我会在while内发布代码:

while((s = in.nextLine()) != null) {
    s = s.toLowerCase();
    Scanner line = new Scanner(s);
    a = line.next();
    if(a.equals("word")) {
        k++;
    }
}

Proper way of figuring out when Scanner runs out of input is checking hasNextLine() condition. 确定Scanner何时耗尽输入的正确方法是检查hasNextLine()条件。 Use this loop to read a sequence of strings that includes empty lines: 使用此循环读取包含空行的字符串序列:

Scanner in = new Scanner(System.in);
while(in.hasNextLine()) {
    String s = in.nextLine();
    System.out.println(s);
}

Demo. 演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM