需要帮助确定扫描仪的行结束

我的程序中有一个扫描程序,它读取部分文件并将其格式化为HTML。 当我正在阅读我的文件时,我需要知道如何让扫描仪知道它在一行的末尾并开始写入下一行。

这是我的代码的相关部分,如果我遗漏了任何内容,请告诉我:

//scanner object to read the input file Scanner sc = new Scanner(file); //filewriter object for writing to the output file FileWriter fWrite = new FileWriter(outFile); //Reads in the input file 1 word at a time and decides how to ////add it to the output file while (sc.hasNext() == true) { String tempString = sc.next(); if (colorMap.containsKey(tempString) == true) { String word = tempString; String color = colorMap.get(word); String codeOut = colorize(word, color); fWrite.write(codeOut + " "); } else { fWrite.write(tempString + " "); } } //closes the files reader.close(); fWrite.close(); sc.close(); 

好的,我发现了sc.nextLine();但我仍然不知道如何确定我何时在一行的末尾。

如果您只想使用Scanner,则需要创建一个临时字符串,将其实例化为数据网格的nextLine()(因此它只返回它跳过的行)和一个扫描临时字符串的新Scanner对象。 这样你只使用那一行,并且hasNext()不会返回误报(这不是一个误报,因为这是它的意图,但在你的情况下,它在技术上是这样)。 您只需将nextLine()保留在第一个扫描仪并更改临时字符串,然后使用第二个扫描仪扫描每个新行等。

行通常由\n\r分隔。所以如果你需要检查它,你可以尝试这样做,虽然我不知道为什么你想要,因为你已经使用nextLine()来读取整个线。

如果您担心hasNext()不适用于您的特定情况(不确定为什么它不会Scanner.hasNextLine()则有Scanner.hasNextLine() )。

你可以使用方法hasNextLine逐行迭代文件而不是逐字迭代,然后用空格分割行,并对单词进行操作

这是使用hasNextLine和split的相同代码

 //scanner object to read the input file Scanner sc = new Scanner(file); //filewriter object for writing to the output file FileWriter fWrite = new FileWriter(outFile); //get the line separator for the current platform String newLine = System.getProperty("line.separator"); //Reads in the input file 1 word at a time and decides how to ////add it to the output file while (sc.hasNextLine()) { // split the line by whitespaces [ \t\n\x0B\f\r] String[] words = sc.nextLine().split("\\s"); for(String word : words) { if (colorMap.containsKey(word)) { String color = colorMap.get(word); String codeOut = colorize(word, color); fWrite.write(codeOut + " "); } else { fWrite.write(word + " "); } } fWrite.write(newLine); } //closes the files reader.close(); fWrite.close(); sc.close(); 

哇我已经使用java 10年了,从未听说过扫描仪! 默认情况下它似乎使用空格分隔符,因此您无法判断何时出现行尾。

看起来您可以更改扫描仪的分隔符 – 请参阅扫描仪类的示例:

  String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close();