2012-02-08 55 views
4

我在我的程序中有一個掃描儀讀取部分文件和格式爲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();,但我仍然不知道如何確定我什麼時候在一行的結尾。

+0

提示:使您的文章標題成爲特定問題。 – nes1983 2012-02-08 23:18:16

+3

當你在結束sc.hasNext()將是假的,不是嗎? – kosa 2012-02-08 23:18:55

+0

只是要清楚,你確定你不想知道如何讓'FileWriter'開始寫在另一行?從您的帖子可以採取這種方式,因爲掃描儀具有您需要的功能。 – 2012-02-08 23:37:18

回答

5

如果你只想使用掃描儀,你需要創建一個臨時字符串,它實例化nextLine()數據網格的(所以它僅返回它跳過線)和一個新的Scanner對象掃描溫度串。這樣,你只使用那條線,hasNext()不會返回誤報(這不是真正的誤報,因爲這就是它的意圖,但在你的情況下,它在技術上是)。您只需保持nextLine()爲第一臺掃描儀並更改臨時字符串,第二臺掃描儀掃描每一條新線等。

1

哇我一直在使用Java 10年,從來沒有聽說過掃描儀! 默認情況下,它似乎使用空格分隔符,因此無法確定行結束的時間。

貌似可以改變掃描儀的分隔符 - 見Scanner Class的例子:

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(); 
1

線通常由\n\r delimitted所以如果你需要檢查它,你可以嘗試做的是方式,但我不知道你爲什麼想要,因爲你已經在使用nextLine()來閱讀整行。

Scanner.hasNextLine()如果你擔心hasNext()不適用於你的具體情況(不知道爲什麼它不會)。

1

可以使用方法hasNextLine迭代通過行,而不是一字一句文件中的行,然後分裂由空格線和字上

這裏你的操作是使用hasNextLine相同的代碼和分裂

//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(); 
+0

謝謝你,這真的很有幫助! – 2012-02-09 00:17:08