有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

克隆如何制作java扫描仪的副本?

我正在用扫描器读取一个java文件。在阅读过程中,我想在读取文件时在数组中保存特殊段落,因此我需要使用额外的扫描器来完成。我不能使用一个扫描仪,因为两个扫描仪处理文件的方式不同(职责不同)。在下面的代码中,我如何复制扫描

    Scanner scan = new Scanner("test.txt");
    while(scan.hasNext())
    {
          String token = scan.next();   
          if(token.compare("START")==0)
          {
              Scanner temp = scan; //How can I make a copy of scan? 
              //scan.clone() does not work
              String curVal =temp.next();
              while(curVal.compare("END") != 0)
              {
                   ...
                   curVal =temp.next() //scan should not go to the next value
              }
          }   
      }

      Example:

      1H2i345
      Thi67s
      START
      I am5678 special bla790b bla...
      END
      We are continuing.

      output:
      String special_para ="I am5678 special bla790b bla..."
      The scan should remove all the numbers (it is just an example what scan does is much more complicated)

共 (2) 个答案

  1. # 1 楼答案

    我想你不需要第二台扫描仪。您只需要添加一个标志和一个新条件。(除非我误解了,而且你需要回到文件的开头。)

    bool insideStartBlock = false;
    Scanner scan = new Scanner("test.txt");
    while(scan.hasNext())
    {
        String token = scan.next();   
        if("START".equals(token))
        {
            insideStartBlock = true;
        }
        else if ("END".equals(token)
        {
            insideStartBlock = false;
        }
        else if (insideStartBlock)
        {
            ...
            <do work based on token>
            ...
        }
    }