【问题标题】:How to insert elements from a file into an ArrayList starting from a specific position?如何从特定位置开始将文件中的元素插入到 ArrayList 中?
【发布时间】:2016-02-27 18:23:00
【问题描述】:

我正在尝试跳过文件的第一行和最后一行,并将其余信息插入到 ArrayList 中。这是我将文件中的所有元素插入到 ArrayList 中的农场。

 CodonSequence cs = new CodonSequence();
 try {
        Scanner scanner = new Scanner(new File("testSequence.txt"));
        while (scanner.hasNextLine()) {
            cs.addNucleotide(scanner.nextLine());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

【问题讨论】:

    标签: java arraylist


    【解决方案1】:
     ArrayList<String> arrayList = new ArrayList<String>();
     BufferedReader reader = new BufferedReader(new FileReader(somepath));
     reader.readLine(); // this will read the first line
     String line1=null;
     while ((line1 = reader.readLine()) != null){ //loop will run from 2nd line until the end
            arrayList.add(scanner.nextLine());
     }
    

    我不确定您的 CodonSequence 是什么,但如果您将第二行直到最后一行存储在 ArrayList 中,您只需删除最后一个元素:

    arrayList.remove(arrayList.size() - 1);
    

    几次搜索不会有什么坏处。

    BufferedReader to skip first line

    Java - remove last known item from ArrayList

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      简单调用

      scanner.nextLine();
      

      在任何处理之前执行一次。

      在循环结束时,做

       Scanner.nextLine();
      

      最简单的方法可能是将您的数据集合包含在 if 语句中以检查scanner.next() 是否不为空:

        try {
                  Scanner scanner = new Scanner(new File("testSequence.txt"));
                  scanner.nextLine();//this would read the first line from the text file
                  while (scanner.hasNextLine()) {
                  if(!scanner.next().equals("")&&!scanner.next()==null){
                      cs.addNucleotide(scanner.nextLine());
                     }
                  }
              } catch (FileNotFoundException e) {
                  e.printStackTrace();
              }
      

      【讨论】:

        【解决方案3】:

        我找到了解决问题的方法。我不得不补充:

        scanner.nextLine();
        

        在我的 while 循环之前跳过第一行。

        【讨论】:

          猜你喜欢
          • 2011-03-22
          • 2013-09-30
          • 1970-01-01
          • 2011-10-27
          • 1970-01-01
          • 2021-03-19
          • 2012-10-30
          • 2014-03-30
          相关资源
          最近更新 更多