簡體   English   中英

如何在java中將CSV文件轉換為整數數組?

[英]How can I convert CSV file into an integer array in java?

我有一個包含整數的 CSV 文件:
.csv

我將其轉換為 String 數組:

try (BufferedReader br = new BufferedReader(new FileReader("x.csv"))) {
        String line;
        while ((line = br.readLine()) != null) {
            String[] values = line.split("\n");
            x_values.add(Arrays.asList(values));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

輸出是這樣的:輸出

但我想將值用作整數並找到它們的平均值。 我怎樣才能做到這一點?

您將行解析為String值,而不是Integers 從您的圖像來看,您的整數采用指數表示法,這意味着您必須首先將它們解析為雙精度數,然后將它們轉換為整數:

    List<Integer> x_values = new ArrayList<>();

    try (BufferedReader br = new BufferedReader(new FileReader("x.csv"))) {
        String line;
        while ((line = br.readLine()) != null) {
            String[] values = line.split("\n");
            List<Integer> intValues = Arrays.asList(values).stream()
                    .map(Double::parseDouble) // parse x.xxE+02 to xxx.0
                    .map(Double::intValue) // xxx.0 to integer xxx
                    .collect(Collectors.toList()); // back to List
            x_values.addAll(intValues);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

您應該確保您的 csv 文件只包含整數,否則請改用List<Double> x_values並跳過 int 轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM