2015-11-25 55 views
0

我想跳过文件的第一行和最后一行,并将剩余的信息插入到ArrayList中。这里是我有这样的农场插入文件中的所有元素到一个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(); 
    } 

回答

0

简单地调用

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

希望这有助于。

0

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

scanner.nextLine(); 

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

相关问题