2012-02-08 37 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