所以我的CSV文件中包含像在Excel我如何從CSV數據的第二行開始掃描到鏈接列表?
speed period warning pair
1 26 1 1 1
2 26 1 1 1
3 26 1 1 1
4 26 1 1 1
在我的掃描儀文件的東西,我有
public class scanner {
public static void main(String[] args) throws IOException {
// open file input stream
BufferedReader reader = new BufferedReader(new FileReader(
"amis.csv"));
// read file line by line
String line = null;
Scanner scanner = null;
int index = 0;
List<amis> empList = new ArrayList<>();
while ((line = reader.readLine()) != null) {
amis emp = new amis();
scanner = new Scanner(line);
scanner.useDelimiter(",");
while (scanner.hasNext()) {
String data = scanner.next();
if (index == 0) {
emp.setId(data);
} else if (index == 4) {
emp.setPair(data);
} else if (index == 3) {
emp.setWarning(data);
} else if (index == 2) {
emp.setPeriod(data);
}else if (index == 1) {
emp.setSpeed(data);
}else {
System.out.println("invalid data::" + data);
}
index++;
}
index = 0;
empList.add(emp);
}
//close reader
reader.close();
System.out.println(empList);
}
但我的鏈表的輸出將顯示
ID = 「」 :: Pair =「pair」:: Warning =「warning」:: Period =「period」:: Speed =「speed」,
ID =「1」:: Pair = 1 :: Warning = 1 :: Period = 1 :: Speed = 26,
ID =「2」:: Pair = 1 :: Warning = 1 :: Period = 1 :: Speed = 26,
ID =「3」:: Pair = 1 :: Warning = 1 ::週期= 1級::速度= 26,
ID = 「4」 ::對= 1個::警告= 1個::週期= 1 ::速度= 26,
如何我剛剛從一開始第二排。
在你的'while'循環之前調用'reader.readLine();'。 –
你真的必須閱讀這樣的csv文件嗎?如果沒有使用[commons-csv](https://commons.apache.org/proper/commons-csv/)。如果是,請嘗試使用推薦的文件閱讀方式:[Java試用資源](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) – adgon92
@AndyTurner謝謝!這解決了它 – computer