从java中读取文件,但输出会跳过其他所有行

时间:2014-09-27 15:40:14

标签: java

我正在尝试读取文件并以特定格式打印出结果。打印时,它只打印其他所有条目。在while循环中,我尝试切换if语句并将0更改为-1然后计数++但它没有工作。

  try
  {
     File f = new File("BaseballNames1.csv");
     FileReader fr = new FileReader(f);
     BufferedReader br = new BufferedReader(fr);

     ArrayList<String> players = new ArrayList<String>();
     String line;
     int count = 0;

     while((line = br.readLine()) != null)
     {
        if(count == 0)
        {
           count++;
           continue;
        }
        players.add(br.readLine());
     }

     for(String p : players)
     {
        String[] player = new String[7];
        player = p.split(",");

        first = player[0].trim();
        last = player[1].trim();
        birthDay = Integer.parseInt(player[2].trim());
        birthMonth = Integer.parseInt(player[3].trim());
        birthYear = Integer.parseInt(player[4].trim());
        weight = Integer.parseInt(player[5].trim());
        height = Double.parseDouble(player[6].trim());
        name = first + " " + last;
        birthday = birthMonth + "/" + birthDay + "/" + birthYear;
        System.out.println(name + "\t" + birthday + "\t" + weight + "\t" + height);
        //System.out.printf("First & Last Name %3s Birthdate %3s Weight %3s Height\n", name, birthday, weight, height);
     }
  }
  catch(Exception e)
  {
     e.getMessage();
  }

2 个答案:

答案 0 :(得分:2)

我认为你的问题就在这里:

while((line = br.readLine()) != null)
{
    if(count == 0)
    {
       count++;
       continue;
    }
    players.add(br.readLine());
}

您每次都在阅读一个新行,即使您已阅读过一行。你想要这个:

while((line = br.readLine()) != null)
{
    if(count == 0)
    {
       count++;
       continue;
    }
    players.add(line); //The important change is here.
}

答案 1 :(得分:1)

更改

players.add(br.readLine());

players.add(line);

您的版本会将下一行读取并写入players,而不是当前行。