只有 txt 文件的最后一行被放入数组

Only last line from txt file is put into the array

我的代码有问题。我试图从 txt 文件中逐行读取,然后将这些行添加到列表中。我的问题是只有文件的最后一行被添加到列表中。

这是我的扫描仪代码:

public void readFile() throws FileNotFoundException, IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));

    String line;

    while ((line = br.readLine()) != null) {
        cyclistList = (List) Arrays.asList(line);
        System.out.println(line);
    }
    br.close();
}

我可以很好地打印列表,但是当我尝试从 txt 文件逐行添加到列表中时,它只会添加最后一行。

这是txt文件的内容,也是用System.out.println方法打印出来的:

[A.CONTADOR TCS ESP 00:09:48    2   45]
[A.DELAPLACE    BSE FRA 03:11:28    1   15]
[A.DEMARE   FDJ FRA 04:05:28    0   43]
[A.FONSECA  BSE FRA 03:53:13    0   18]
[A.GENIEZ   FDJ FRA 03:42:57    27  31]
[A.GERARD   BSE FRA 04:02:06    0   0]
[A.GREIPEL  LTS ALL 04:03:28    0   366]
[A.GRIVKO   AST UKR 02:38:06    0   51]
[A.HANSEN   LTS AUS 03:45:18    0   2]
[A.KRISTOFF KAT NOR 04:01:06    0   90]
[A.LOSADA   KAT ESP 02:32:30    0   7]
[A.MALORI   MOV ITA 03:37:28    0   11]
[A.TALANSKY TCG USA 00:22:06    22  32]
[A.TIMMER   TGA HOL 04:05:30    0   0]
[A.TULIK    EUC FRA 03:18:24    0   11]
[A.VALVERDE MOV ESP 00:05:25    72  103]
[A.VUILLERMOZ   ALM FRA 01:28:29    2   52]
[A.YATES    OGE GBR 02:16:36    17  42]
[B.COQUARD  EUC FRA 03:42:36    0   152]
[B.FEILLU   BSE FRA 03:23:11    0   17]
[B.HUZARSKI BOA POL 03:38:06    1   27]
[B.JUNGELS  TFR LUX 01:33:21    16  76]
[B.MOLLEMA  TFR HOL 00:15:14    0   38]
[B.NAULEAU  EUC FRA 04:40:12    0   2]
[B.TANKINK  TLJ HOL 02:30:12    0   0]
[B.VAUGRENARD   FDJ FRA 03:43:08    0   20]
[C.FROOME   SKY GBR 00:00:00    119 139]
[C.GAUTIER  EUC FRA 01:51:51    4   54]
[C.LAPORTE  COF FRA 03:59:10    0   17]
[C.RIBLON   ALM FRA 02:48:19    1   23]
[D.CARUSO   BMC ITA 02:26:32    8   21]
[D.CIMOLAI  LAM ITA 04:33:21    0   34]
[D.GAUDIN   ALM FRA 04:16:13    0   0]
[D.GRUZDEV  AST KAZ 04:01:12    0   0]
[D.MARTIN   TCG IRL 02:03:37    27  72]
[D.NAVARR GARCIA    COF ESP 02:43:34    0   9]
[D.OSS      BMC ITA 03:22:14    0   16]
[D.TEKLEHAIMANOT    MTN ERY 02:16:15    8   51]
[D.VAN BAARLE   TCG HOL 04:18:40    0   13]
[D.WYSS     BMC SUI 02:37:17    0   0]
[E.BOASSON HAGEN    MTN NOR 03:08:02    2   79]
[E.BUCHMANN BOA ALL 03:08:47    16  15]
[F.BRUN     BSE FRA 04:10:32    0   18]
[F.POZZATO  LAM ITA 03:58:20    1   0]
[F.SENECHAL COF FRA 04:04:06    0   -5]
[F.VACHON   BSE FRA 03:15:01    0   11]
[G.CARUSO   KAT ITA 03:17:03    0   1]
[G.IZAGIRRE MOV ESP 01:41:34    28  26]
[G.PREIDLER TGA AUT 03:14:14    15  14]
[G.RAST     TFR SUI 03:29:00    0   0]
[G.SOUPE    COF FRA 03:55:35    0   34]
[G.THOMAS   SKY GBR 00:31:39    22  37]
[H.ZUBELDIA TFR ESP 02:36:50    0   0]
[I.ERVITI   MOV ESP 03:47:14    0   6]
[I.STANNARD SKY GBR 03:59:37    0   0]
[J.ARREDO MORENO    TFR COL 03:56:49    0   10]
[J.BAKELANTS    ALM BEL 01:16:36    2   50]
[J.BARTA    BOA RTC 01:26:56    20  47]
[J.CASTROVIEJO  MOV ESP 01:26:05    0   31]
[J.DEBUSSCHERE  LTS BEL 04:16:06    0   29]
[J.DEGENKOLB    TGA ALL 03:39:43    1   298]
[J.FUGLSANG AST DAN 01:25:23    64  34]
[J.GUARNIERI    KAT ITA 04:22:20    0   24]
[J.HERRADA  MOV ESP 02:40:06    3   1]
[J.JANS RENSBURG    MTN AFS 02:18:16    0   0]
[J.MENDES   BOA POR 04:07:47    0   0]
[J.PANTANO  IAM COL 01:09:08    2   48]
[J.PERAUD   ALM FRA 02:35:10    0   -5]
[J.RODRIGUEZ    KAT ESP 01:36:07    78  71]
[J.ROY      FDJ FRA 03:32:12    6   8]
[J.SERPA PEREZ  LAM COL 03:54:25    0   20]
[J.SIMON    COF FRA 03:19:53    12  18]
[J.VAN EMDEN    TLJ HOL 03:54:19    0   11]
[J.VERMOTE  EQS BEL 03:50:32    0   0]
[K.DE KORT  TGA HOL 02:57:05    0   30]
[K.DURASEK  LAM CRO 03:02:14    13  26]
[K.KOREN    TCG SLV 02:51:44    1   14]
[K.VANBILSEN    COF BEL 04:41:27    3   37]
[L.BAK      LTS DAN 01:56:57    14  9]
[L.DURBRIDGE    OGE AUS 04:25:03    0   11]
[L.KONIG    SKY RTC 02:53:09    0   0]
[L.MATE MARDONES    COF ESP 02:10:12    0   29]
[L.ROWE     SKY GBR 04:04:45    0   3]
[L.TEN DAM  TLJ HOL 03:18:43    0   -5]
[L.WESTRA   AST HOL 03:03:09    3   25]
[M.BONO     LAM ITA 03:52:17    0   0]
[M.BRANDLE  IAM AUT 04:37:36    0   9]
[M.CAVENDISH    EQS GBR 04:12:05    0   206]
[M.CHEREL   ALM FRA 01:05:00    24  8]
[M.ELMIGER  IAM SUI 03:26:47    0   0]
[M.FRANK    IAM SUI 00:15:39    4   24]
[M.GOLAS    EQS POL 03:21:17    0   9]
[M.HALLER   KAT AUT 03:59:04    1   13]
[M.IRIZAR   TFR ESP 03:19:44    0   0]
[M.GHEBREMEDHIN MTN ERY 03:10:36    0   26]
[M.LADAGNOUS    FDJ FRA 02:53:22    9   13]
[M.MATTHEWS OGE AUS 04:26:33    0   25]
[M.QUINZIATO    BMC ITA 03:53:21    0   0]
[M.ROGERS   TCS AUS 01:56:13    1   32]
[M.SCARPONI AST ITA 02:05:03    0   0]
[M.SCHAR    BMC SUI 02:31:13    1   1]
[M.SIEBERG  LTS ALL 04:24:52    0   11]
[M.TOSATTO  TCS ITA 04:01:15    0   0]
[M.TRENTIN  EQS ITA 03:50:59    1   44]
[M.WYSS     IAM SUI 02:34:38    0   0]
[N.EDET     COF FRA 03:42:42    16  34]
[N.OLIVEIRA LAM POR 02:15:32    0   10]
[N.QUINTANA MOV COL 00:01:12    108 80]
[N.ROCHE    SKY IRL 01:54:08    0   16]
[P.FEDRIGO  BSE FRA 02:22:54    0   37]
[P.MARTENS  TLJ ALL 03:04:52    0   20]
[P.PERICHON BSE FRA 03:05:48    0   61]
[P.QUEMENEUR    EUC FRA 02:57:19    0   46]
[P.ROLLAND  EUC FRA 00:17:30    74  73]
[P.SAGAN    TCS SLQ 02:14:55    3   432]
[P.VOSS     BOA ALL 03:24:53    0   7]
[P.WEENING  OGE HOL 04:15:20    0   -5]
[R.BARDET   ALM FRA 00:16:00    90  74]
[R.CURVERS  TGA HOL 03:35:40    0   46]
[R.DENNIS   BMC AUS 03:27:34    1   36]
[R.GESINK   TLJ HOL 00:10:47    32  53]
[R.HESJEDAL TCG CAN 02:04:37    41  43]
[R.HOLLENSTEIN  IAM SUI 02:58:30    0   0]
[R.JANS RENSBURG    MTN AFS 03:21:30    0   14]
[R.KREUZIGER    TCS RTC 01:02:51    12  17]
[R.MAJKA    TCS POL 01:35:06    40  28]
[R.NAVARDAUSKAS TCG LIT 04:14:40    20  44]
[R.PLAZA    LAM ESP 01:38:22    11  86]
[R.PORTE    SKY AUS 02:16:05    58  38]
[R.SICARD   EUC FRA 01:51:32    23  32]
[R.URAN     EQS COL 02:08:20    5   55]
[R.VALLS FERRI  LAM ESP 03:03:11    0   5]
[S.CHAVANEL FDJ FRA 04:56:59    2   39]
[S.CLEMENT  IAM HOL 02:33:42    0   37]
[S.CUMMINGS MTN GBR 03:12:23    2   49]
[S.DEVOLDER TFR BEL 04:21:31    0   0]
[S.GESCHKE  TGA ALL 01:58:14    22  78]
[S.KRUIJSWIJK   TLJ HOL 01:21:27    10  10]
[S.PAUWELS  MTN BEL 00:31:03    55  43]
[S.SANCHEZ  BMC ESP 00:22:50    0   10]
[S.TUFT     OGE CAN 04:48:08    0   0]
[S.VANMARCKE    TLJ BEL 03:31:15    8   5]
[S.YATES    OGE GBR 03:16:04    0   40]
[T.DE GENDT LTS BEL 02:48:02    6   90]
[T.FARRAR   MTN USA 04:32:32    0   12]
[T.GALLOPIN LTS FRA 01:40:44    8   85]
[T.KANGERT  AST EST 01:24:58    0   0]
[T.LEEZER   TLJ HOL 04:26:47    0   0]
[T.MACHADO  KAT POR 02:54:31    0   0]
[T.PINOT    FDJ FRA 00:38:52    82  113]
[T.VOECKLER EUC FRA 02:14:08    23  28]
[T.WELLENS  LTS BEL 03:59:39    0   -1]
[V.NIBALI   AST ITA 00:08:36    53  49]
[W.ANACONA  MOV COL 02:31:14    33  29]
[W.BARGUIL  TGA FRA 00:31:15    0   25]
[W.KELDERMAN    TLJ HOL 03:04:07    1   20]
[W.POELS    SKY HOL 02:12:44    18  9]
[Y.GENE     EUC FRA 04:04:56    0   0]
[Z.STYBAR   EQS RTC 03:30:13    0   78]

这是我使用 cyclistList = (List) Arrays.asList(sc.nextLine()); 代码得到的输出:

[Z.STYBAR   EQS RTC 03:30:13    0   78]

编辑: 我的不好,我忘了添加一些东西。我已经在 class:

中有了一个列表
private List<RacingCyclist> cyclistList = new ArrayList<>();

此列表实现了一个 Comparable:

public class RacingCyclist implements Comparable<RacingCyclist> {
//...
}

所以方法 cyclistList.add(); 不起作用,因为我收到以下错误:

"No suitable method found for add(String) Method Collection.add(RacingCyclist) is not applicable (argument mismatch; String cannot be converted to RacingCyclist)"

问题是,您每次循环都会创建一个新的 List

这是问题所在:cyclistList = (List) Arrays.asList(line);。在这一行中,您创建了一个新的 List,这就是您只保留最后一个元素的原因,因为在最后一次迭代中,您创建了一个仅包含该元素的列表。

要解决它,改变这个:

public void readFile() throws FileNotFoundException, IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));

    String line;

    while ((line = br.readLine()) != null) {
        cyclistList = (List) Arrays.asList(line);
        System.out.println(line);
    }
    br.close();
}

为此:

public void readFile() throws FileNotFoundException, IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));

    String line;
    ArrayList<String> list = new ArrayList<String>();

    while ((line = br.readLine()) != null) {
        list.add(line);
        System.out.println(line);
    }
    br.close();
}

这样您将拥有一个包含所有数据的 ArrayList,而不是每次迭代都创建一个新的 List


编辑: 从您的编辑中,您试图将 String 添加到自定义对象的 ArrayList 中,在您的情况下是RacingCyclist(或者这是自定义列表?如果是,您正在尝试创建列表列表)。

如果这个对象可以容纳一个 String,那么它可能应该有一个 getter 和一个 setter,所以在你的循环中使用它们,如:

customObject.setLine(line);
cyclistList.add(customObject);

现在,如果您的自定义对象是另一个列表(为什么?),那么它可能应该包含可以包含 String 的其他对象,或者它本身可以包含 String。但我的猜测是你可能不应该这样做,使用一个简单的 ArrayList 而不是实现 Comparable 的 holder 对象,这样 ArrayList 将能够对你的元素进行排序。


第二次编辑: 好的,我对您的自定义做了一些修改class。开始了。

RacingCyclist.java

package opg3_tour;

/**
 *
 * @author erso
 */
public class RacingCyclist implements Comparable<RacingCyclist> {

    private String name;
    private String team;
    private String country;

    private String time;
    private int mountains;
    private int points;

    public RacingCyclist(String name, String team, String country, String time, int mountains, int points) {
        this.name = name;
        this.team = team;
        this.country = country;
        this.time = time;
        this.mountains = mountains;
        this.points = points;
    }

    // Empty constructor.
    public RacingCyclist() { }

    // Getters

    public String getName() {
        return name;
    }

    public String getTeam() {
        return team;
    }

    public String getCountry() {
        return country;
    }

    public String getTime() {
        return time;
    }

    public int getMountains() {
        return mountains;
    }

    public int getPoints() {
        return points;
    }

    // Setters - They update the data on your Object.

    public void setName(String name) {
        this.name = name;
    }

    public void setTeam(String team) {
        this.team = team;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public void setMountains(int mountains) {
        this.mountains = mountains;
    }

    public void setPoints(int points) {
        this.points = points;
    }

// This method parses lines on the following format: [A.CONTADOR TCS ESP 00:09:48    2   45]
    public void parseLine(String str) {
        str = str.replaceAll("^ +| +$| (?= )", ""); // Removing extra spaces between words.
        str = str.replace("[","");
        str = str.replace("]","");
        String[] lines = str.split(" "); // Breaking the String into lines.

        setName(lines[0]);
        setTeam(lines[1]);
        setCountry(lines[2]);
        setTime(lines[3]);
        setMountains(Integer.parseInt(lines[4]));
        setPoints(Integer.parseInt(lines[5]));
    }

    @Override
    public String toString() {
        return name + " " + team + " " + country + " " + time + " " + mountains + " " + points + "\n";
    }

    @Override
    public int compareTo(RacingCyclist o) {
        if (Integer.parseInt(getTime()) > Integer.parseInt(o.getTime())){ 
            return 1;
        }
        else if (Integer.parseInt(getTime()) < Integer.parseInt(o.getTime())){
            return -1;
        }
        else  {
            return this.name.compareTo(o.name); 
        }
    }
}

我创建了一个空的构造函数和一个名为 parseLine(String line) 的方法,它可以获取文件的那一行并将值分配给自定义对象 RacingCyclist.

然后,您的循环应该如下所示:

while ((line = br.readLine()) != null) {
    RacingCyclist obj = new RacingCyclist();
    obj.parseLine(line);
    cyclistList.add(obj);
    System.out.println(line);
}

这样您将创建 RacingCyclist 对象的新实例,并且 parseLine 方法将分解该字符串并获取其值并将其分配给您的对象内部变量。

那是因为你不是在添加列表(使用"add"方法)而是一直在创建一个新列表。