3 回答

TA貢獻1725條經驗 獲得超8個贊
兩點:-
1 - 如下更改您的主列表。您不應該創建通用列表(原始類型)。如果您將列表創建為原始類型,您將能夠輸入任何數據類型。由于可能存在多種數據類型列表,因此會產生問題。
2 - 當您進入 while 循環時,創建/分配新引用到子列表,然后將其添加到主列表。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CSVReader {
public static void main(String[] args) {
String csvFile = "E:\\country.csv";
String line = "";
String cvsSplitBy = ",";
List<String> sub = new ArrayList<String>();
List<List<String>> master = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
sub = new ArrayList<String>();
sub.add(line);
master.add(new ArrayList<String>(sub));
// System.out.println(sub);
sub.remove(0);
// System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(master);
}
}

TA貢獻1883條經驗 獲得超3個贊
嘗試將變量聲明移到subwhile 塊上。
String csvFile = "E:\\country.csv";
String line = "";
String cvsSplitBy = ",";
List<List> master = new ArrayList<List>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
List<String> sub = new ArrayList<String>();
sub.add(line);
master.add(sub);
// System.out.println(sub);
// sub.remove(0);
// System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(master);

TA貢獻1794條經驗 獲得超8個贊
你可以這樣做
public static List<String[]> getTestData(String fileName) {
List<String[]> records = new ArrayList<String[]>();
try {
String record;
BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
while ((record = file.readLine()) != null) {
System.out.println(record);
String fields[] = record.split(",");
records.add(fields);
}
file.close();
return records;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
添加回答
舉報