Help us understand the problem. What is going on with this article?

Android, Kotlin: CSVの読み書き

  • Minimum SDK: API 23
  • Android Studio 4.0.1
  • Kotlin 1.4.0
  • opencsv Version: 5.2

Android, KotlinでCSVの読み書きを、opencsvを使って実装します。
CSVの操作を説明するために、StringReader, StringWriterを使って実装していますので、必要に応じてFileReader, FileWriter, InputStreamReader, OutputStreamWriterに置き換えて実装してください。

SDカードへのファイル読み書きはこちらを参照ください。→ Android: SDカード上のファイルへの読み書き

準備

opencsvライブラリ取り込み

build.gradle(app)
dependencies {
    implementation 'com.opencsv:opencsv:5.2'
}

配列を使った方法

書き込み

実装
        val strWriter = StringWriter()
        val csvWriter = CSVWriter(strWriter)
        csvWriter.writeNext(arrayOf("三幸太郎", "45", "男"))
        csvWriter.writeNext(arrayOf("三幸次郎", "44", "男"))
        csvWriter.writeNext(arrayOf("三幸花子", "35", "女"))
        println(strWriter.toString())
出力
"三幸太郎","45","男"
"三幸次郎","44","男"
"三幸花子","35","女"

読み込み

読み込み元は、先ほど作成したCSVテキスト(strWriter)

実装
        val strReader = StringReader(strWriter.toString())
        val csvIter = CSVIterator(CSVReader(strReader))
        for (row in csvIter) {
            for (col in row) {
                print(col)
            }
        }

オブジェクト(Bean)を使った方法

データ定義

初期値はいるみたいです。

CSVヘッダー無し
data class User(
    @CsvBindByPosition(position = 0)
    val name: String = "",

    @CsvBindByPosition(position = 1)
    val age: Int = 0,

    @CsvBindByPosition(position = 2)
    val gender: String = ""
)
CSVヘッダーあり
data class User(
    @CsvBindByName(column = "名前", required = true)
    val name: String = "",

    @CsvBindByName(column = "年齢", required = true)
    val age: Int = 0,

    @CsvBindByName(column = "性別", required = true)
    val gender: String = ""
)

書き込み

実装
        val strWriter = StringWriter()
        val beanWriter = StatefulBeanToCsvBuilder<User>(strWriter).build()
        beanWriter.write(User("三幸太郎", 45, "男"))
        beanWriter.write(User("三幸次郎", 44, "男"))
        beanWriter.write(User("三幸花子", 35, "女"))
        println(strWriter.toString())
出力(ヘッダー無し)
"三幸太郎","45","男"
"三幸次郎","44","男"
"三幸花子","35","女"
出力(ヘッダーあり)
"名前","年齢","性別"
"三幸太郎","45","男"
"三幸次郎","44","男"
"三幸花子","35","女"

読み込み

読み込み元は、先ほど作成したCSVテキスト(strWriter)

実装
        val strReader = StringReader(strWriter.toString())
        val beanList = CsvToBeanBuilder<User>(strReader)
            .withType(User::class.java)
            .withIgnoreLeadingWhiteSpace(true)
            .build()
            .parse()
        for (user in beanList) {
            println(String.format("%s, %d, %s", user.name, user.age, user.gender))
        }
nozaki-sankosc
東京都中央区にある三幸システムの野崎です。 Android, iOS, PHPなどのライブラリを公開していきたいと思います。
https://www.sankosc.co.jp
sankosc
東京都中央区にある三幸システム株式会社です。PHP, Android, iOS, Windows, AWS, Lambdaなどで開発をしています。新しい技術、基本的な技術など共有していきます。
https://www.sankosc.co.jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした