簡體   English   中英

如何用Scanner確定一行的結尾?

[英]How to determine the end of a line with a Scanner?

我的程序中有一個掃描程序,它讀取部分文件並將其格式化為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()保留在第一個掃描儀並更改臨時字符串,然后使用第二個掃描儀掃描每個新行等。

哇我已經使用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();

行通常由\\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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM