簡體   English   中英

將 CSV 文件轉換為二維數組

[英]Converting CSV File Into 2D Array

我在一維數組中有一個我的想法的例子。 它只會 output 列。 我的想法是使用一個二維數組來 select 的行和列。 這是我的代碼:

String fName = "c:\\csv\\myfile.csv";
String thisLine; 
int count=0; 
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i=0; 

while ((thisLine = myInput.readLine()) != null) {
     String strar[] = thisLine.split(";");
     out.println(strar[1]); // Here column 2
}

我的文件.csv

Id;name
E1;Tim
A1;Tom

Output:

名字蒂姆湯姆

我只是將拆分結果( String[] )添加到List然后如果您真的想要它作為二維數組,那么在事后將其轉換。

List<String[]> lines = new ArrayList<String[]>();
while ((thisLine = myInput.readLine()) != null) {
     lines.add(thisLine.split(";"));
}

// convert our list to a String array.
String[][] array = new String[lines.size()][0];
lines.toArray(array);

首先我們不知道 csv 文件中有多少行。 所以無法確定二維數組的長度。 我們必須根據這種情況增加數組的大小。 但是,通常不可能用 java 重新調整數組的大小。 因此,當我們需要重新調整數組大小時,我們創建新數組並復制源數組的內容。

為您解決:

int i = 0;//line count of csv
String[][] data = new String[0][];//csv data line count=0 initially
while ((thisLine = myInput.readLine()) != null) {
    ++i;//increment the line count when new line found

    String[][] newdata = new String[i][2];//create new array for data

    String strar[] = thisLine.split(";");//get contents of line as an array
    newdata[i - 1] = strar;//add new line to the array

    System.arraycopy(data, 0, newdata, 0, i - 1);//copy previously read values to new array
    data = newdata;//set new array as csv data
}

創建測試以查看 csv 數據:

for (String[] strings : data) {
    for (String string : strings) {
        System.out.print("\t" + string);
    }
    System.out.println();
}

輸出:

Id  name
E1  Tim
A1  Tom

我會使用動態結構來讀取所有行。 此外,您應該使用 try-resource 塊來自動關閉流。

public static String[][] readCSV(String path) throws FileNotFoundException, IOException {
    try (FileReader fr = new FileReader(path);
            BufferedReader br = new BufferedReader(fr)) {
        Collection<String[]> lines = new ArrayList<>();
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            lines.add(line.split(";"));
        }
        return lines.toArray(new String[lines.size()][]);
    }
}

這是我實現的代碼:

String fileName = "myfile.csv";
List<List<String>> list = new ArrayList<List<String>>();
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String[] headers = line.split(";");
for(String header: headers) {
    List<String> subList = new ArrayList<String>();
    subList.add(header);
    list.add(subList);
}
while((line = br.readLine()) != null) {
    String[] elems = line.split(";");
    for(int i = 0; i < elems.length; i++) {
        list.get(i).add(elems[i]);
    }
}
br.close();
int rows = list.size();
int cols = list.get(0).size();
String[][] array2D = new String[rows][cols];
for(int row = 0; row < rows; row++) {
    for(int col = 0; col < cols; col++) {
        array2D[row][col] = list.get(row).get(col);
    }
}

array2D是你想要的。

最好使用一維字符串數組的 ArrayList,而不是二維字符串數組。

String fName = "c:\\csv\\myfile.csv";
String thisLine;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
ArrayList<String[]> strar = new ArrayList<String[]>();

while ((thisLine = myInput.readLine()) != null) {
    strar.add(thisLine.split(";"));
}

注意:您還需要在此處處理 IOException。

我想你應該看到這個代碼:

  1. 讀取csv文件后。
  2. 閱讀列表中的所有行。
  3. 定義兩個數組,一個是一維數組,第二個是二維數組
  4. for 循環到 csv 文件中的記錄數(第一個循環)
  5. 將每條記錄分解為一維數組
  6. for 在第一個循環內循環到 csv 文件中的列數
  7. 將一維數組中的每個值分配到二維數組中

編碼:

    Path path= Paths.get("url_of_csv_file");
    List<String> arr= Files.readAllLines(path);
    String[] arr2; 
    String[][] arr3= new String[records][columns];
    for(int i=0; i<records; i++){
        arr2= arr.get(i).split("\\,");
    for(int j=0; j<columns; j++)
        arr3[i][j]= arr2[j];
    }
    //test case
    for(int i=0; i<records; i++){
        for(int j=0; j<columns; j++)
            System.out.print(arr3[i][j]+"  ");
        System.out.println();
    }    
    //read the .csv file and store it in a list of string values
    var DataReader = new BufferedReader(new FileReader(csvPath.toString()));
    String line;
    var Arr = new ArrayList<String>();
    while ((line = DataReader.readLine()) != null) {
        Arr.add(line);
    }

    //break each item in the list to a matrix 
    var TwoDimdata = new String[Arr.size()][Arr.get(0).toString().split(",").length];
    for (var i = 0; i < TwoDimdata.length; i++) {
        for (var j = 0; j < TwoDimdata[0].length; j++) {
            var arr = Arr.get(i).split(",");
            TwoDimdata[i][j] = arr[j];
        }
    }

暫無
暫無

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

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