[英]While printing array list only last value is printed
我正在嘗試讀取僅在一列中具有值的 CSV 文件,例如
11111 22222 33333 44444
我能夠讀取文件,但是當我打印僅打印最后一個值的值時,即 44444。以下是我的代碼,請幫助我獲取列表中的所有值並打印:-
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ReadCVS {
public static void main(String[] args) {
ReadCVS obj = new ReadCVS();
obj.run();
}
@SuppressWarnings("unchecked")
public void run() {
String csvFile = "/C:/Users/SONY/Desktop/Book1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
List<String[]> list=new ArrayList<String[]>();
try {
br = new BufferedReader(new FileReader(csvFile));
String[] country = null ;
while ((line = br.readLine()) != null) {
country= line.split(cvsSplitBy);
list.add(country);
System.out.println(Arrays.toString(country));
}
for(int i = 0; i < country.length; i++) {
System.out.println(Arrays.toString(country));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
問題是您在第二個for loop
中打印country
,其中包含最后一列的值,在您的情況下為44444
嘗試這樣的事情。
List<String[]> list = new ArrayList();
try {
list.add(new String[]{"a","b"});
list.add(new String[]{"c","d"});
for (String[] str: list) {
System.out.println(Arrays.toString(str));
}
} catch (Exception e) {}
輸出:
[a, b]
[c, d]
這是一個試圖模擬你的通用示例。 根據您的要求進行更改。 永遠不要像我在上面的例子中那樣讓異常未被捕獲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.