私のコードでは奇妙なことが起きていますが、何が起こっているのか分かりません。私は次のようなファイルを持っています:Javaリストは最後のレコードを追加し続け、ファイル内のレコード数を複製します。
id;state;city;total_pop;avg_temp
1;Florida;;120000;76
2;Michigan;Detroit;330000;54
3;New Jersey;Newark;;34
私のjavaパーサーは結果としてマップのリストを作成して返します。しかし、返されるのは、ファイル内の最後のレコードがファイル内の行数だけ繰り返されることだけです。誰かが私のコードを見て、何が起こっているかについて私に啓発することができますか?前もって感謝します。ここで
public class FileParserUtil {
public List<Map<String, String>> parseFile(String fileName, char seperator)
throws IOException {
CSVReader reader = new CSVReader(new FileReader(fileName), seperator);
Map<String, String> record = new HashMap<String, String>();
List<Map<String, String>> rows = new ArrayList<Map<String, String>>();
String[] header = reader.readNext();
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
for (int i = 0; i < header.length; i++) {
record.put(header[i], nextLine[i]);
}
System.out.println("--------Here is the record: ---------");
System.out.println(record);
rows.add(record);
System.out.println("--------Here are the rows: ---------");
System.out.println(rows);
}
reader.close();
return rows;
}
}
は、mainメソッドから上記実行のコンソール出力です...
--------Here is the record: ---------
{id=1, avg_temp=76, state=Florida, total_pop=120000, city=}
--------Here are the rows: ---------
[{id=1, avg_temp=76, state=Florida, total_pop=120000, city=}]
--------Here is the record: ---------
{id=2, avg_temp=54, state=Michigan, total_pop=330000, city=Detroit}
--------Here are the rows: ---------
[{id=2, avg_temp=54, state=Michigan, total_pop=330000, city=Detroit}, {id=2, avg_temp=54, state=Michigan, total_pop=330000, city=Detroit}]
--------Here is the record: ---------
{id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}
--------Here are the rows: ---------
[{id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}, {id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}, {id=3, avg_temp=34, state=New Jersey, total_pop=, city=Newark}]
ありがとうございます。 –
あなたも大歓迎です...ファイルから値を保存し、そのクラスの新しいインスタンスをすべてのレコードに作成する新しいクラスを作成することをお勧めします。そうすれば、コードはもっときれいになります。 –
これをスピードアップする方法はありますか?それは遅いようです。 –