簡體   English   中英

java CSV文件到數組

[英]java CSV file to array

我是java的新手,但我似乎無法想出這個。 我有一個CSV文件,格式如下:

String1,String2
String1,String2
String1,String2
String1,String2

每一行都是成對的。 第二行是新記錄,與第三行相同。 在真實的單詞中,CSV文件的大小會發生變化,有時會變為3條記錄,或4條甚至10條。

我的問題是如何將值讀入數組並動態調整大小? 我想,首先我們必須解析csv文件,獲取記錄/元素的數量,然后根據該大小創建數組,然后再次通過CSV並將其存儲在數組中。

我只是不確定如何做到這一點。

任何幫助,將不勝感激。

您可以使用ArrayList而不是Array。 ArrayList是動態數組。 恩。

Scanner scan = new Scanner(new File("yourfile"));
ArrayList<String[]> records = new ArrayList<String[]>();
String[] record = new String[2];
while(scan.hasNext())
{
    record = scan.nextLine().split(",");
    records.add(record);
}
//now records has your records.
//here is a way to loop through the records (process)
    for(String[] temp : records)
    {
        for(String temp1 : temp)
        {
            System.out.print(temp1 + " ");
        }
        System.out.print("\n");
    }

只需將“yourfile”替換為文件的絕對路徑即可。

你可以這樣做。

如果你不喜歡第一個例子,更傳統的for循環用於處理數據:

    for(int i = 0; i < records.size(); i++)
    {
        for(int j = 0; j < records.get(i).length; j++)
        {
            System.out.print(records.get(i)[j] + " ");
        }
        System.out.print("\n");
    }

兩個for循環都在做同樣的事情。

您可以使用開源庫uniVocity-parsers將CSV簡單地讀入2行數組中。

請參考以下代碼作為示例:

public static void main(String[] args) throws FileNotFoundException {

    /**
     * ---------------------------------------
     * Read CSV rows into 2-dimensional array
     * ---------------------------------------
     */

    // 1st, creates a CSV parser with the configs
    CsvParser parser = new CsvParser(new CsvParserSettings());

    // 2nd, parses all rows from the CSV file into a 2-dimensional array
    List<String[]> resolvedData = parser.parseAll(new FileReader("/examples/example.csv"));

    // 3rd, process the 2-dimensional array with business logic
    // ......
}

TL;博士

  • 使用Java Collections而不是數組(特別是ListSet )在添加項目時自動展開。
  • 定義一個類來保存從CSV讀取的數據,為讀取的每一行實例化一個對象。
  • 使用Apache Commons CSV庫來幫助閱讀/編寫CSV文件。

用於保存數據的類

定義一個類來保存從CSV中讀取的每一行的數據。 讓我們使用具有給定名稱和姓氏的Person類,比問題中的示例更具體。

package work.basil.example;

public class Person {
    public String givenName, surname;

    public Person ( String givenName , String surname ) {
        this.givenName = givenName;
        this.surname = surname;
    }

    @Override
    public String toString ( ) {
        return "Person{ " +
                "givenName='" + givenName + '\'' +
                " | surname='" + surname + '\'' +
                " }";
    }
}

集合,而不是數組

使用Java Collections通常比使用純數組更好。 這些系列更靈活,功能更強大。 請參閱Oracle教程

在這里,我們將使用List接口來收集從CSV文件中讀入的數據實例化的每個Person對象。 我們使用List的具體ArrayList實現,它在后台使用數組。 與您的問題相關的重要部分是您可以將對象添加到List 而不必擔心調整大小 List實現負責任何所需的大小調整。

如果您恰好知道要填充的列表的大致大小,則可以在創建List時提供可選的初始容量作為提示。

Apache Commons CSV

Apache Commons CSV庫可以很好地讀取和編寫CSV和制表符分隔格式的幾種變體。

示例應用

這是一個示例應用程序,位於單個PersoIo.java文件中。 Io是輸入輸出的縮寫。

示例數據。

GivenName,Surname
Alice,Albert
Bob,Babin
Charlie,Comtois
Darlene,Deschamps

源代碼。

package work.basil.example;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class PersonIo {
    public static void main ( String[] args ) {
        PersonIo app = new PersonIo();
        app.doIt();
    }

    private void doIt ( ) {
        Path path = Paths.get( "/Users/basilbourque/people.csv" );
        List < Person > people = this.read( path );
        System.out.println( "People: \n" + people );
    }

    private List < Person > read ( final Path path ) {
        Objects.requireNonNull( path );
        if ( Files.notExists( path ) ) {
            System.out.println( "ERROR - no file found for path: " + path + ". Message # de1f0be7-901f-4b57-85ae-3eecac66c8f6." );
        }

        List < Person > people = List.of(); // Default to empty list.
        try {
            // Hold data read from file.
            int initialCapacity = ( int ) Files.lines( path ).count();
            people = new ArrayList <>( initialCapacity );

            // Read CSV file.
            BufferedReader reader = Files.newBufferedReader( path );
            Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
            for ( CSVRecord record : records ) {
                // GivenName,Surname
                // Alice,Albert
                // Bob,Babin
                // Charlie,Comtois
                // Darlene,Deschamps
                String givenName = record.get( "GivenName" );
                String surname = record.get( "Surname" );

                // Use read data to instantiate.
                Person p = new Person( givenName , surname );

                // Collect
                people.add( p ); // For real work, you would define a class to hold these values.
            }

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


}

跑步時

人:

[Person {givenName ='Alice'| surname ='Albert'},Person {givenName ='Bob'| surname ='Babin'},Person {givenName ='Charlie'| surname ='Comtois'},Person {givenName ='Darlene'| surname ='Deschamps'}]

暫無
暫無

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

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