首页 > 解决方案 > 从文件读取到数组但最后一行覆盖所有其他行

问题描述

所以我希望这是我最后的手段,因为我在编写主要代码方面取得了足够的进展,如果没有其他办法,我只会来这里。

String line = "";
try 
{   
  BufferedReader br = new BufferedReader (new FileReader("league.txt"));
  FootballClub club = new FootballClub();
    
  while ( ( line = br.readLine() ) != null )
  {
    String[] FC = line.split(",");
    club.setName(FC[0]);
    club.setLocation(FC[1]);
    club.setMatchesPlayed(Integer.parseInt(FC[2]));
    club.setWins(Integer.parseInt(FC[3]));
    club.setDraws(Integer.parseInt(FC[4]));
    club.setLosses(Integer.parseInt(FC[5]));
    club.setGoalsScored(Integer.parseInt(FC[6]));
    club.setGoalsAgainst(Integer.parseInt(FC[7]));
    club.setGoalDifference(Integer.parseInt(FC[8]));
    club.setPoints(Integer.parseInt(FC[9]));

    league.add(club);
  } 
    
  br.close(); 
} 
catch (FileNotFoundException e) { } 
catch (IOException e){ }

这是我从文本文件读取到数组的代码。文本文件如下:

Chelsea,London,0,0,0,0,0,0,0,0       
WestHam,London,0,0,0,0,0,0,0,0

问题是当我测试程序时,两个球杆被添加到数组中,但是第一行的值被第二行覆盖。我一直在尝试先添加一行,然后再添加第二行,直到没有行,但我似乎很幸运。我一直在到处寻找尝试修复它,但没有运气,它看起来确实很容易修复,但我筋疲力尽,找不到它。任何指针和建议将不胜感激。

标签: javaarraysbufferedreader

解决方案


您需要在每次迭代时创建该类的新实例,否则您会一直在同一对象上设置属性,因此只会存储最后一行。

while ((line = br.readLine()) != null){
     String[] FC = line.split(",");
     FootballClub club = new FootballClub();
     //...
}

推荐阅读