diff --git a/.asf.yaml b/.asf.yaml
new file mode 100644
index 0000000000..cdb8cd101b
--- /dev/null
+++ b/.asf.yaml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+github:
+ description: "Apache Commons CSV"
+ homepage: https://commons.apache.org/csv/
+
+notifications:
+ commits: commits@commons.apache.org
+ issues: issues@commons.apache.org
+ pullrequests: issues@commons.apache.org
+ jira_options: link label
+ jobs: notifications@commons.apache.org
+ # commits_bot_dependabot: dependabot@commons.apache.org
+ issues_bot_dependabot: dependabot@commons.apache.org
+ pullrequests_bot_dependabot: dependabot@commons.apache.org
+ issues_bot_codecov-commenter: notifications@commons.apache.org
+ pullrequests_bot_codecov-commenter: notifications@commons.apache.org
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000..f42866e4bd
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+* text=auto
diff --git a/.travis.yml b/.github/GH-ROBOTS.txt
similarity index 79%
rename from .travis.yml
rename to .github/GH-ROBOTS.txt
index ecb839d953..64a88674fe 100644
--- a/.travis.yml
+++ b/.github/GH-ROBOTS.txt
@@ -5,7 +5,7 @@
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
@@ -13,12 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-language: java
-
-jdk:
- - oraclejdk8
- - oraclejdk9
-
-after_success:
- - mvn -B -V clean test jacoco:report coveralls:report -Ptravis-jacoco
-
\ No newline at end of file
+# Keeps on creating FUD PRs in test code
+# Does not follow Apache disclosure policies
+User-agent: JLLeitschuh/security-research
+Disallow: *
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000000..90ec55f742
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,25 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+version: 2
+updates:
+ - package-ecosystem: "maven"
+ directory: "/"
+ schedule:
+ interval: "quarterly"
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "quarterly"
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000000..9ff35c83e7
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,30 @@
+
+
+Thanks for your contribution to [Apache Commons](https://commons.apache.org/)! Your help is appreciated!
+
+Before you push a pull request, review this list:
+
+- [ ] Read the [contribution guidelines](CONTRIBUTING.md) for this project.
+- [ ] Read the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) if you use Artificial Intelligence (AI).
+- [ ] I used AI to create any part of, or all of, this pull request. Which AI tool was used to create this pull request, and to what extent did it contribute?
+- [ ] Run a successful build using the default [Maven](https://maven.apache.org/) goal with `mvn`; that's `mvn` on the command line by itself.
+- [ ] Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible, but it is a best practice.
+- [ ] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
+- [ ] Each commit in the pull request should have a meaningful subject line and body. Note that a maintainer may squash commits during the merge process.
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
new file mode 100644
index 0000000000..cca38e5121
--- /dev/null
+++ b/.github/workflows/codeql-analysis.yml
@@ -0,0 +1,86 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+name: "CodeQL"
+
+on:
+ push:
+ branches: [ master ]
+ pull_request:
+ # The branches below must be a subset of the branches above
+ branches: [ master ]
+ schedule:
+ - cron: '33 9 * * 4'
+
+permissions:
+ contents: read
+
+jobs:
+ analyze:
+ name: Analyze
+ runs-on: ubuntu-latest
+ permissions:
+ actions: read
+ contents: read
+ security-events: write
+
+ strategy:
+ max-parallel: 20
+ fail-fast: false
+ matrix:
+ language: [ 'java' ]
+ # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
+ # Learn more about CodeQL language support at https://git.io/codeql-language-support
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+ with:
+ persist-credentials: false
+ - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 #v6.1.0
+ with:
+ path: ~/.m2/repository
+ key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
+ restore-keys: |
+ ${{ runner.os }}-maven-
+
+ # Initializes the CodeQL tools for scanning.
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
+ with:
+ languages: ${{ matrix.language }}
+ # If you wish to specify custom queries, you can do so here or in a config file.
+ # By default, queries listed here will override any specified in a config file.
+ # Prefix the list here with "+" to use these queries and those in the config file.
+ # queries: ./path/to/local/query, your-org/your-repo/queries@main
+
+ # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
+ # If this step fails, then you should remove it and run the build manually (see below)
+ - name: Autobuild
+ uses: github/codeql-action/autobuild@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
+
+ # โน๏ธ Command-line programs to run using the OS shell.
+ # ๐ https://git.io/JvXDl
+
+ # โ๏ธ If the Autobuild fails above, remove it and uncomment the following three lines
+ # and modify them (or add more) to build your code if your project
+ # uses a compiled language
+
+ #- run: |
+ # make bootstrap
+ # make release
+
+ - name: Perform CodeQL Analysis
+ uses: github/codeql-action/analyze@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml
new file mode 100644
index 0000000000..7bc02bdd23
--- /dev/null
+++ b/.github/workflows/dependency-review.yml
@@ -0,0 +1,31 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+name: 'Dependency Review'
+on: [pull_request]
+
+permissions:
+ contents: read
+
+jobs:
+ dependency-review:
+ runs-on: ubuntu-latest
+ steps:
+ - name: 'Checkout Repository'
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+ - name: 'Dependency Review PR'
+ uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml
new file mode 100644
index 0000000000..17ba7dd386
--- /dev/null
+++ b/.github/workflows/maven.yml
@@ -0,0 +1,61 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+name: Java CI
+
+on:
+ push:
+ branches:
+ - 'master'
+ pull_request: {}
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+
+ runs-on: ${{ matrix.os }}
+ continue-on-error: ${{ matrix.experimental }}
+ strategy:
+ max-parallel: 20
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest]
+ java: [ 8, 11, 17, 21, 25, 26 ]
+ experimental: [false]
+ # Keep the same parameter order as the matrix above
+ include:
+ - os: ubuntu-latest
+ java: 27-ea
+ experimental: true
+
+ steps:
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+ with:
+ persist-credentials: false
+ - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 #v6.1.0
+ with:
+ path: ~/.m2/repository
+ key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
+ restore-keys: |
+ ${{ runner.os }}-maven-
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
+ with:
+ distribution: ${{ runner.os == 'macOS' && matrix.java == '8' && 'zulu' || 'temurin' }}
+ java-version: ${{ matrix.java }}
+ - name: Build with Maven
+ run: mvn -Ddoclint=all --show-version --batch-mode --no-transfer-progress
diff --git a/.github/workflows/scorecards-analysis.yml b/.github/workflows/scorecards-analysis.yml
new file mode 100644
index 0000000000..e1868cb462
--- /dev/null
+++ b/.github/workflows/scorecards-analysis.yml
@@ -0,0 +1,69 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache license, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the license for the specific language governing permissions and
+# limitations under the license.
+
+name: "Scorecards supply-chain security"
+
+on:
+ branch_protection_rule:
+ schedule:
+ - cron: "30 1 * * 6" # Weekly on Saturdays
+ push:
+ branches: [ "master" ]
+
+permissions: read-all
+
+jobs:
+
+ analysis:
+
+ name: "Scorecards analysis"
+ runs-on: ubuntu-latest
+ permissions:
+ # Needed to upload the results to the code-scanning dashboard.
+ security-events: write
+ actions: read
+ id-token: write # This is required for requesting the JWT
+ contents: read # This is required for actions/checkout
+
+ steps:
+
+ - name: "Checkout code"
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # 7.0.0
+ with:
+ persist-credentials: false
+
+ - name: "Run analysis"
+ uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # 2.4.3
+ with:
+ results_file: results.sarif
+ results_format: sarif
+ # A read-only PAT token, which is sufficient for the action to function.
+ # The relevant discussion: https://github.com/ossf/scorecard-action/issues/188
+ repo_token: ${{ secrets.GITHUB_TOKEN }}
+ # Publish the results for public repositories to enable scorecard badges.
+ # For more details: https://github.com/ossf/scorecard-action#publishing-results
+ publish_results: true
+
+ - name: "Upload artifact"
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: SARIF file
+ path: results.sarif
+ retention-days: 5
+
+ - name: "Upload to code-scanning"
+ uses: github/codeql-action/upload-sarif@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
+ with:
+ sarif_file: results.sarif
diff --git a/.gitignore b/.gitignore
index c9e48537cc..2ff17ae4a8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,4 @@
-### https://raw.github.com/github/gitignore/14b7566ce157ce95b07006466bacee160f242284/maven.gitignore
+### https://github.com/github/gitignore/blob/master/Maven.gitignore
target/
pom.xml.tag
@@ -6,8 +6,23 @@ pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
+dependency-reduced-pom.xml
+buildNumber.properties
+.mvn/timing.properties
+# https://github.com/takari/maven-wrapper#usage-without-binary-jar
+.mvn/wrapper/maven-wrapper.jar
-/.classpath
-/.project
-/.settings/
+.classpath
+.project
+.settings/
+
+/.idea/
+*.iml
+
+/.vscode/
+/.DS_Store
+
+# NetBeans files
+nb-configuration.xml
+nbactions.xml
diff --git a/BENCHMARK.md b/BENCHMARK.md
new file mode 100644
index 0000000000..c45918a289
--- /dev/null
+++ b/BENCHMARK.md
@@ -0,0 +1,79 @@
+
+
+Apache Commons CSV Benchmark
+===================
+
+Apache Commons CSV includes a Java Microbenchmark Harness (JMH) for testing various implementations
+of CSV processing.
+
+Prerequisite
+-------------
+
+The Skife CSV implementation is not available in Maven Central and therefore must be manually
+installed into the local Maven repository. Run the falling script to download and install
+the JAR file (~1MB).
+
+```shell
+./benchmark-prereq.sh
+```
+
+Benchmarks
+-------------
+
+Benchmark Name | CSV Parser | Description
+--------------- | --------------- | -------------
+read | Java JDK | Use BufferedReader to perform a line count
+scan | Java JDK | Use Scanner to perform a line count
+split | Java JDK | Use BufferedReader to split each line on a delimiter
+parseCommonsCSV | commons-csv | Use CSVFormat to split each line on a delimiter
+parseGenJavaCSV | generation-java | Use CsvReader to split each line on a delimiter
+parseJavaCSV | java-csv | Use CsvReader to split each line on a delimiter
+parseOpenCSV | open-csv | Use CSVReader to split each line on a delimiter
+parseSkifeCSV | skife-csv | Use CSVReader to split each line on a delimiter
+parseSuperCSV | super-csv | Use CsvListReader to split each line on a delimiter
+
+Running the Tests
+-------------
+
+```shell
+# Run all benchmark tests
+mvn test -Pbenchmark
+
+# Run a specific benchmark test
+mvn test -Pbenchmark -Dbenchmark=
+
+# Example of running basic "read" benchmark
+mvn test -Pbenchmark -Dbenchmark=read
+```
+
+Performance Test
+-------------
+
+Apache Commons CSV includes a stand-alone performance test which only covers commons-csv.
+
+```shell
+# Run the performance test
+mvn test -Dtest=PerformanceTest
+```
+
+> :warning: This performance test does not use JMH; it uses simple timing metrics.
+
+Performance Test Harness
+-------------
+
+CSV offers a secondary performance test harness located at: `org.apache.commons.csv.PerformanceTest`
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000..b4342f33ca
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,17 @@
+
+The Apache code of conduct page is [https://www.apache.org/foundation/policies/conduct.html](https://www.apache.org/foundation/policies/conduct.html).
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5d133b3747..3423e18ad2 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -6,7 +6,7 @@
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -25,7 +25,7 @@
| commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+======================================================================+
| |
- | 1) Re-generate using: mvn commons:contributing-md |
+ | 1) Re-generate using: mvn commons-build:contributing-md |
| |
| 2) Set the following properties in the component's pom: |
| - commons.jira.id (required, alphabetic, upper case) |
@@ -41,38 +41,40 @@
Contributing to Apache Commons CSV
======================
-You have found a bug or you have an idea for a cool new feature? Contributing code is a great way to give something back to
-the open source community. Before you dig right into the code there are a few guidelines that we need contributors to
-follow so that we can have a chance of keeping on top of things.
+Have you found a bug or have an idea for a cool new feature? Contributing code is a great way to give something back to the open-source community.
+Before you dig right into the code, we need contributors to follow a few guidelines to have a chance of keeping on top of things.
Getting Started
---------------
+ Make sure you have a [JIRA account](https://issues.apache.org/jira/).
-+ Make sure you have a [GitHub account](https://github.com/signup/free).
++ Make sure you have a [GitHub account](https://github.com/signup). This is not essential, but makes providing patches much easier.
+ If you're planning to implement a new feature it makes sense to discuss your changes on the [dev list](https://commons.apache.org/mail-lists.html) first. This way you can make sure you're not wasting your time on something that isn't considered to be in Apache Commons CSV's scope.
+ Submit a [Jira Ticket][jira] for your issue, assuming one does not already exist.
+ Clearly describe the issue including steps to reproduce when it is a bug.
+ Make sure you fill in the earliest version that you know has the issue.
+ Find the corresponding [repository on GitHub](https://github.com/apache/?query=commons-),
-[fork](https://help.github.com/articles/fork-a-repo/) and check out your forked repository.
+[fork](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo) and check out your forked repository. If you don't have a GitHub account, you can still clone the Commons repository.
Making Changes
--------------
+ Create a _topic branch_ for your isolated work.
- * Usually you should base your branch on the `master` or `trunk` branch.
- * A good topic branch name can be the JIRA bug id plus a keyword, e.g. `CSV-123-InputStream`.
+ * Usually you should base your branch from the `master` branch.
+ * A good topic branch name can be the JIRA bug ID plus a keyword, e.g. `CSV-123-InputStream`.
* If you have submitted multiple JIRA issues, try to maintain separate branches and pull requests.
+ Make commits of logical units.
* Make sure your commit messages are meaningful and in the proper format. Your commit message should contain the key of the JIRA issue.
- * e.g. `CSV-123: Close input stream earlier`
+ * For example, `[CSV-123] Close input stream sooner`
+ Respect the original code style:
- + Only use spaces for indentation.
+ + Only use spaces for indentation; you can check for unnecessary whitespace with `git diff` before committing.
+ Create minimal diffs - disable _On Save_ actions like _Reformat Source Code_ or _Organize Imports_. If you feel the source code should be reformatted create a separate PR for this change first.
- + Check for unnecessary whitespace with `git diff` -- check before committing.
-+ Make sure you have added the necessary tests for your changes, typically in `src/test/java`.
-+ Run all the tests with `mvn clean verify` to assure nothing else was accidentally broken.
++ Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible but is a best practice.
+Unit tests are typically in the `src/test/java` directory.
++ Run a successful build using the default [Maven](https://maven.apache.org/) goal with `mvn`; that's `mvn` on the command line by itself.
++ Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
++ Each commit in the pull request should have a meaningful subject line and body. Note that commits might be squashed by a maintainer on merge.
+
Making Trivial Changes
----------------------
@@ -80,7 +82,7 @@ Making Trivial Changes
The JIRA tickets are used to generate the changelog for the next release.
For changes of a trivial nature to comments and documentation, it is not always necessary to create a new ticket in JIRA.
-In this case, it is appropriate to start the first line of a commit with '(doc)' instead of a ticket number.
+In this case, it is appropriate to start the first line of a commit with '[doc]' or '[javadoc]' instead of a ticket number.
Submitting Changes
@@ -106,10 +108,9 @@ Additional Resources
+ [Contributing patches](https://commons.apache.org/patches.html)
+ [Apache Commons CSV JIRA project page][jira]
+ [Contributor License Agreement][cla]
-+ [General GitHub documentation](https://help.github.com/)
-+ [GitHub pull request documentation](https://help.github.com/articles/creating-a-pull-request/)
++ [General GitHub documentation](https://docs.github.com/)
++ [GitHub pull request documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request)
+ [Apache Commons Twitter Account](https://twitter.com/ApacheCommons)
-+ `#apache-commons` IRC channel on `irc.freenode.net`
[cla]:https://www.apache.org/licenses/#clas
[jira]:https://issues.apache.org/jira/browse/CSV
diff --git a/LICENSE-header.txt b/LICENSE-header.txt
deleted file mode 100644
index ae6f28c4a1..0000000000
--- a/LICENSE-header.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
diff --git a/LICENSE.txt b/LICENSE.txt
index d645695673..ff9ad4530f 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -193,7 +193,7 @@
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
diff --git a/NOTICE.txt b/NOTICE.txt
index 85a48c863d..06d3824a28 100644
--- a/NOTICE.txt
+++ b/NOTICE.txt
@@ -1,5 +1,5 @@
Apache Commons CSV
-Copyright 2005-2018 The Apache Software Foundation
+Copyright 2005-2026 The Apache Software Foundation
This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
+The Apache Software Foundation (https://www.apache.org/).
diff --git a/README.md b/README.md
index 32385abfc1..f30de4b9c9 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -25,7 +25,7 @@
| commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+======================================================================+
| |
- | 1) Re-generate using: mvn commons:readme-md |
+ | 1) Re-generate using: mvn commons-build:readme-md |
| |
| 2) Set the following properties in the component's pom: |
| - commons.componentid (required, alphabetic, lower case) |
@@ -43,64 +43,77 @@
Apache Commons CSV
===================
-[](https://travis-ci.org/apache/commons-csv)
-[](https://coveralls.io/r/apache/commons-csv)
-[](https://maven-badges.herokuapp.com/maven-central/org.apache.commons/commons-csv/)
-[](https://javadoc.io/doc/org.apache.commons/commons-csv/1.6)
+[](https://github.com/apache/commons-csv/actions/workflows/maven.yml)
+[](https://search.maven.org/artifact/org.apache.commons/commons-csv)
+[](https://javadoc.io/doc/org.apache.commons/commons-csv/1.14.1)
+[](https://github.com/apache/commons-csv/actions/workflows/codeql-analysis.yml)
+[](https://api.securityscorecards.dev/projects/github.com/apache/commons-csv)
-The Apache Commons CSV library provides a simple interface for reading and writing
-CSV files of various types.
+The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
Documentation
-------------
More information can be found on the [Apache Commons CSV homepage](https://commons.apache.org/proper/commons-csv).
-The [Javadoc](https://commons.apache.org/proper/commons-csv/javadocs/api-release) can be browsed.
-Questions related to the usage of Apache Commons CSV should be posted to the [user mailing list][ml].
+The [Javadoc](https://commons.apache.org/proper/commons-csv/apidocs) can be browsed.
+Questions related to the usage of Apache Commons CSV should be posted to the [user mailing list](https://commons.apache.org/mail-lists.html).
-Where can I get the latest release?
------------------------------------
+Getting the latest release
+--------------------------
You can download source and binaries from our [download page](https://commons.apache.org/proper/commons-csv/download_csv.cgi).
-Alternatively you can pull it from the central Maven repositories:
+Alternatively, you can pull it from the central Maven repositories:
```xml
org.apache.commonscommons-csv
- 1.6
+ 1.14.1
```
+Building
+--------
+
+Building requires a Java JDK and [Apache Maven](https://maven.apache.org/).
+The required Java version is found in the `pom.xml` as the `maven.compiler.source` property.
+
+From a command shell, run `mvn` without arguments to invoke the default Maven goal to run all tests and checks.
+
Contributing
------------
-We accept Pull Requests via GitHub. The [developer mailing list][ml] is the main channel of communication for contributors.
+We accept Pull Requests via GitHub. The [developer mailing list](https://commons.apache.org/mail-lists.html) is the main channel of communication for contributors.
There are some guidelines which will make applying PRs easier for us:
+ No tabs! Please use spaces for indentation.
-+ Respect the code style.
++ Respect the existing code style for each file.
+ Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change.
-+ Provide JUnit tests for your changes and make sure your changes don't break any existing tests by running ```mvn clean test```.
++ Provide JUnit tests for your changes and make sure your changes don't break any existing tests by running `mvn`.
++ Before you pushing a PR, run `mvn` (by itself), this runs the default goal, which contains all build checks.
++ To see the code coverage report, regardless of coverage failures, run `mvn clean site -Dcommons.jacoco.haltOnFailure=false -Pjacoco`
If you plan to contribute on a regular basis, please consider filing a [contributor license agreement](https://www.apache.org/licenses/#clas).
You can learn more about contributing via GitHub in our [contribution guidelines](CONTRIBUTING.md).
License
-------
-This code is under the [Apache Licence v2](https://www.apache.org/licenses/LICENSE-2.0).
+This code is licensed under the [Apache License v2](https://www.apache.org/licenses/LICENSE-2.0).
See the `NOTICE.txt` file for required notices and attributions.
-Donations
----------
-You like Apache Commons CSV? Then [donate back to the ASF](https://www.apache.org/foundation/contributing.html) to support the development.
+Donating
+--------
+You like Apache Commons CSV? Then [donate back to the ASF](https://www.apache.org/foundation/contributing.html) to support development.
Additional Resources
--------------------
+ [Apache Commons Homepage](https://commons.apache.org/)
+ [Apache Issue Tracker (JIRA)](https://issues.apache.org/jira/browse/CSV)
++ [Apache Commons Slack Channel](https://the-asf.slack.com/archives/C60NVB8AD)
+ [Apache Commons Twitter Account](https://twitter.com/ApacheCommons)
-+ `#apache-commons` IRC channel on `irc.freenode.org`
-[ml]:https://commons.apache.org/mail-lists.html
+Apache Commons Components
+-------------------------
+
+Please see the [list of components](https://commons.apache.org/components.html)
diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt
index 34973539f1..bfeb4bb8de 100644
--- a/RELEASE-NOTES.txt
+++ b/RELEASE-NOTES.txt
@@ -1,9 +1,576 @@
- Apache Commons CSV
- Version 1.6
- Release Notes
+Apache Commons CSV 1.14.1 Release Notes
+---------------------------------------
+The Apache Commons CSV team is pleased to announce the release of Apache Commons CSV 1.14.1.
-INTRODUCTION:
+
+This document contains the release notes for the 1.14.1 version of Apache Commons CSV.
+Commons CSV reads and writes files in Comma Separated Value (CSV) format variations.
+
+Commons CSV requires at least Java 8.
+
+The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
+
+This is a feature and maintenance release. Java 8 or later is required.
+
+Changes in this version include:
+
+
+Fixed Bugs
+----------
+
+* CSV-318: CSVPrinter.printRecord(Stream) hangs if given a parallel stream. Thanks to Joseph Shraibman, Gary Gregory.
+* CSV-318: CSVPrinter now uses an internal lock instead of synchronized methods. Thanks to Joseph Shraibman, Gary Gregory.
+* org.apache.commons.csv.CSVPrinter.printRecords(ResultSet) now writes one record at a time using a lock. Thanks to Gary Gregory.
+
+Changes
+-------
+
+* Bump org.apache.commons:commons-parent from 81 to 85 #542. Thanks to Gary Gregory, Dependabot.
+* Bump commons-io:commons-io from 2.18.0 to 2.20.0. Thanks to Gary Gregory.
+* Bump com.opencsv:opencsv from 5.10 to 5.11.2 #545, #551, #553. Thanks to Gary Gregory, Dependabot.
+* Bump org.apache.commons:commons-lang3 from 3.17.0 to 3.18.0 #556. Thanks to Gary Gregory, Dependabot.
+* Bump commons-codec:commons-codec from 1.18.0 to 1.19.0. Thanks to Gary Gregory.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
+
+For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons CSV website:
+
+https://commons.apache.org/proper/commons-csv/
+
+Download page: https://commons.apache.org/proper/commons-csv/download_csv.cgi
+
+Have fun!
+-Apache Commons CSV team
+
+------------------------------------------------------------------------------
+
+Apache Commons CSV 1.14.0 Release Notes
+---------------------------------------
+
+This document contains the release notes for the 1.14.0 version of Apache Commons CSV.
+Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
+
+Commons CSV requires at least Java 8.
+
+The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
+
+This is a feature and maintenance release. Java 8 or later is required.
+
+Changes in this version include:
+
+New Features
+------------
+
+* Define and use Maven property commons.jmh.version. Thanks to Gary Gregory.
+* Add CSVFormat.Builder.setMaxRows(long). Thanks to Gary Gregory.
+* Add CSVFormat.getMaxRows(). Thanks to Gary Gregory.
+* CSVPrinter.printRecords(ResultSet) knows how to use CSVFormat's maxRows. Thanks to Gary Gregory.
+* CSVPrinter.printRecords(Iterable) knows how to use CSVFormat's maxRows. Thanks to Gary Gregory.
+* CSVPrinter.printRecords(Stream) knows how to use CSVFormat's maxRows. Thanks to Gary Gregory.
+* CSVParser.stream() knows how to use CSVFormat's maxRows. Thanks to Gary Gregory.
+* CSVParser.getRecords() knows how to use CSVFormat's maxRows. Thanks to Gary Gregory.
+* CSVParser.iterator() knows how to use CSVFormat's maxRows. Thanks to Gary Gregory.
+
+Fixed Bugs
+----------
+
+* CSV-317: Release history link changed from changes-report.html to changes.html #516. Thanks to Filipe Roque.
+* Remove -nouses directive from maven-bundle-plugin. OSGi package imports now state 'uses' definitions for package imports, this doesn't affect JPMS (from org.apache.commons:commons-parent:80). Thanks to Gary Gregory.
+* CSVParser.parse(URL, Charset, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)). Thanks to Gary Gregory.
+* CSVParser.parse(String, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)). Thanks to Gary Gregory.
+* CSVParser.parse(File, Charset, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)). Thanks to Gary Gregory.
+* CSVParser.parse(Path, Charset, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)). Thanks to Gary Gregory.
+* CSVParser.parse(InputStream, Charset, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)). Thanks to Gary Gregory.
+* CSVParser.parse(*) methods with a null Charset maps to Charset.defaultCharset(). Thanks to Gary Gregory.
+* Fix possible NullPointerException in Token.toString(). Thanks to Gary Gregory.
+
+Changes
+-------
+
+* Bump com.opencsv:opencsv from 5.9 to 5.10. Thanks to Gary Gregory.
+* Bump commons-codec:commons-codec from 1.17.2 to 1.18.0 #522. Thanks to Gary Gregory.
+* Bump org.apache.commons:commons-parent from 79 to 81. Thanks to Gary Gregory.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
+
+For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons CSV website:
+
+https://commons.apache.org/proper/commons-csv/
+
+Download page: https://commons.apache.org/proper/commons-csv/download_csv.cgi
+
+Have fun!
+-Apache Commons CSV team
+
+------------------------------------------------------------------------------
+
+Apache Commons CSV 1.13.0 Release Notes
+---------------------------------------
+
+This document contains the release notes for the 1.13.0 version of Apache Commons CSV.
+Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
+
+Commons CSV requires at least Java 8.
+
+The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
+
+This is a feature and maintenance release. Java 8 or later is required.
+
+Changes in this version include:
+
+New Features
+------------
+
+* CSV-313: Add CSVPrinter.getRecordCount(). Thanks to Gary Gregory.
+* Add and use CSVParser.Builder and builder() and deprecate CSVParser constructors. Thanks to Gary Gregory.
+* CSVFormat.Builder implements Supplier. Thanks to Gary Gregory.
+* Deprecate CSVFormat.Builder.build() for get(). Thanks to Gary Gregory.
+* CSV-196: Track byte position #502. Thanks to Yuzhan Jiang, Gary Gregory.
+
+Fixed Bugs
+----------
+
+* CSV-314: Required OSGi Import-Package version numbers in MANIFEST.MF #504. Thanks to Gary Gregory.
+* CSV-314: CSVParser.nextRecord() should throw CSVException (an IOException subclass) instead of IOException and IllegalStateException, no method signature changes needed. Thanks to Gary Gregory.
+
+Changes
+-------
+
+* Bump org.apache.commons:commons-parent from 76 to 78 #486, #495. Thanks to Gary Gregory, Dependabot.
+* Bump org.codehaus.mojo:taglist-maven-plugin from 3.1.0 to 3.2.1 #493. Thanks to Gary Gregory, Dependabot.
+* Bump commons-io:commons-io from 2.17.0 to 2.18.0 #505. Thanks to Gary Gregory, Dependabot.
+* Bump commons-codec:commons-codec from 1.17.1 to 1.17.2. Thanks to Gary Gregory.
+* Bump org.apache.commons:commons-parent from 78 to 79. Thanks to Gary Gregory.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
+
+For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons CSV website:
+
+https://commons.apache.org/proper/commons-csv/
+
+Download page: https://commons.apache.org/proper/commons-csv/download_csv.cgi
+
+Have fun!
+-Apache Commons CSV team
+
+------------------------------------------------------------------------------
+
+Apache Commons CSV 1.12.0 Release Notes
+---------------------------------------
+
+This document contains the release notes for the 1.12.0 version of Apache Commons CSV.
+Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
+
+Commons CSV requires at least Java 8.
+
+The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
+
+Feature and bug fix release (Java 8 or above)
+
+Changes in this version include:
+
+New Features
+------------
+
+* CSV-270: Add CSVException that extends IOException thrown on invalid input instead of IOException. Thanks to Thomas Kamps, Gary Gregory.
+
+Fixed Bugs
+----------
+
+* Fix PMD issues for port to PMD 7.1.0. Thanks to Gary Gregory.
+* Fix some Javadoc links #442. Thanks to Dรกvid Szigecsรกn, Gary Gregory.
+* Extract duplicated code into a method #444. Thanks to Dรกvid Szigecsรกn.
+* Migrate CSVFormat#print(File, Charset) to NIO #445. Thanks to Dรกvid Szigecsรกn.
+* Fix documentation for CSVFormat private constructor #466. Thanks to Dรกvid Szigecsรกn.
+* CSV-294: CSVFormat does not support explicit " as escape char. Thanks to Joern Huxhorn, Gary Gregory.
+* CSV-150: Escaping is not disableable. Thanks to dota17, Gary Gregory, Jรถrn Huxhorn.
+* Fix Javadoc warnings on Java 23. Thanks to Gary Gregory.
+* Improve parser performance by up to 20%, YMMV. Thanks to Gary Gregory.
+
+Changes
+-------
+
+* Bump commons-codec:commons-codec from 1.16.1 to 1.17.1 #422, #449. Thanks to Dependabot.
+* Bump org.apache.commons:commons-parent from 69 to 75 #435, #452, #465, #468, #475. Thanks to Gary Gregory.
+* Bump org.codehaus.mojo:taglist-maven-plugin from 3.0.0 to 3.1.0 #441. Thanks to Gary Gregory.
+* Bump org.apache.commons:commons-lang3 from 3.14.0 to 3.17.0 #450, #459, #470. Thanks to Gary Gregory.
+* Bump org.hamcrest:hamcrest from 2.2 to 3.0 #455. Thanks to Gary Gregory.
+* Bump commons-io:commons-io from 2.16.1 to 2.17.0 #476. Thanks to Gary Gregory, Dependabot.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
+
+For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons CSV website:
+
+https://commons.apache.org/proper/commons-csv/
+
+Download page: https://commons.apache.org/proper/commons-csv/download_csv.cgi
+
+Have fun!
+-Apache Commons CSV team
+
+------------------------------------------------------------------------------
+
+Apache Commons CSV 1.11.0 Release Notes
+---------------------------------------
+
+This document contains the release notes for the 1.11.0 version of Apache Commons CSV.
+Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
+
+Commons CSV requires at least Java 8.
+
+The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
+
+Feature and bug fix release (Java 8 or above)
+
+Changes in this version include:
+
+New Features
+------------
+
+* CSV-308: [Javadoc] Add example to CSVFormat#setHeaderComments() #344. Thanks to Buddhi De Silva, Gary Gregory.
+* Add and use CSVFormat#setTrailingData(boolean) in CSVFormat.EXCEL for Excel compatibility #303. Thanks to DamjanJovanovic, Gary Gregory.
+* Add and use CSVFormat#setLenientEof(boolean) in CSVFormat.EXCEL for Excel compatibility #303. Thanks to DamjanJovanovic, Gary Gregory.
+
+Fixed Bugs
+----------
+
+* CSV-306: Replace deprecated method in user guide, update external link #324, #325. Thanks to Sam Ng, Bruno P. Kinoshita.
+* Document duplicate header behavior #309. Thanks to Seth Falco, Bruno P. Kinoshita.
+* Add missing docs #328. Thanks to jkbkupczyk.
+* [StepSecurity] CI: Harden GitHub Actions #329, #330. Thanks to step-security-bot.
+* CSV-147: Better error message during faulty CSV record read #347. Thanks to Steven Peterson, Benedikt Ritter, Gary Gregory, Joerg Schaible, Buddhi De Silva, Elliotte Rusty Harold.
+* CSV-310: Misleading error message when QuoteMode set to None #352. Thanks to Buddhi De Silva.
+* CSV-311: OutOfMemory for very long rows despite using column value of type Reader. Thanks to Christian Feuersaenger, Gary Gregory.
+* Use try-with-resources to manage JDBC Clob in CSVPrinter.printRecords(ResultSet). Thanks to Gary Gregory.
+* JDBC Blob columns are now output as Base64 instead of Object#toString(), which usually is InputStream#toString(). Thanks to Gary Gregory.
+* Support unusual Excel use cases: Add support for trailing data after the closing quote, and EOF without a final closing quote #303. Thanks to DamjanJovanovic, Gary Gregory.
+* MongoDB CSV empty first column parsing fix #412. Thanks to Igor Kamyshnikov, Gary Gregory.
+
+Changes
+-------
+
+* Bump commons-io:commons-io: from 2.11.0 to 2.16.1 #408, #413. Thanks to Gary Gregory.
+* Bump commons-parent from 57 to 69 #410. Thanks to Gary Gregory, Dependabot.
+* Bump h2 from 2.1.214 to 2.2.224 #333, #349, #359. Thanks to Dependabot.
+* Bump commons-lang3 from 3.12.0 to 3.14.0. Thanks to Gary Gregory.
+* Update exception message in CSVRecord#getNextRecord() #348. Thanks to Buddhi De Silva, Michael Osipov, Gary Gregory.
+* Bump tests using com.opencsv:opencsv from 5.8 to 5.9 #373. Thanks to Dependabot.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
+
+For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons CSV website:
+
+https://commons.apache.org/proper/commons-csv/
+
+Download page: https://commons.apache.org/proper/commons-csv/download_csv.cgi
+
+Have fun!
+-Apache Commons CSV team
+
+------------------------------------------------------------------------------
+
+Apache Commons CSV 1.10.0 Release Notes
+---------------------------------------
+
+This document contains the release notes for the 1.10.0 version of Apache Commons CSV.
+Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
+
+Commons CSV requires at least Java 8.
+
+The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
+
+Feature and bug fix release (Java 8 or above)
+
+Changes in this version include:
+
+New Features
+------------
+
+* CSV-291: Make CSVRecord#values() public. Thanks to Gary Gregory.
+* CSV-264: Add DuplicateHeaderMode for flexibility with header strictness. #114. Thanks to Sagar Tiwari, Seth Falco, Alex Herbert, Gary Gregory.
+* CSV-295: Support for parallelism in CSVPrinter. Thanks to Gary Gregory.
+* CSV-295: Add CSVPrinter.printRecord[s](Stream). Thanks to Gary Gregory.
+* CSV-304: Add accessors for header/trailer comments #257. Thanks to Peter Hull, Bruno P. Kinoshita, Gary Gregory.
+* Add github/codeql-action.
+
+Fixed Bugs
+----------
+
+* Minor changes #172. Thanks to Arturo Bernal.
+* CSV-292: No Automatic-Module-Name prevents usage in JPMS projects without repacking the JAR. Thanks to Rob Vesse.
+* CSV-288: Fix for multi-char delimiter not working as expected #218. Thanks to Santhsoh, Angus.
+* CSV-269: CSVRecord.get(Enum) should use Enum.name() instead of Enum.toString(). Thanks to Auke te Winkel, Gary Gregory.
+* Allow org.apache.commons.csv.IOUtils.copy(Reader, Appendable, CharBuffer) to compile on Java 11 and run on Java 8. Thanks to Gary Gregory.
+* CSV-300: CSVRecord.toList() does not give write access to the new List. Thanks to Markus Spann, Gary Gregory.
+* CSVParser.getRecords() now throws UncheckedIOException instead of IOException. Thanks to Gary Gregory.
+* CSV-274: Add comments to iterator() and stream() #270. Thanks to Peter Hull, Bruno P. Kinoshita, Gary Gregory.
+* CSV-290: Fix wrong assumptions in PostgreSQL formats #265. Thanks to angusdev, Gary Gregory.
+* Validate input to setDelimiter(String) for empty string #266. Thanks to Mykola Faryma.
+* Bump CSVFormat#serialVersionUID from 1 to 2. Thanks to Dependabot.
+* CSVParser: Identify duplicates in null, empty and blank header names #279. Thanks to Alex Herbert.
+
+Changes
+-------
+
+* Bump actions/cache from 2.1.6 to 3.0.10 #196, #233, #243, #267, #271. Thanks to Dependabot, Gary Gregory.
+* Bump actions/checkout from 2.3.4 to 3.1.0 #188, #195, #220, #272. Thanks to Dependabot, Gary Gregory.
+* Bump actions/setup-java from 2 to 3.5.1. Thanks to Gary Gregory.
+* Bump actions/upload-artifact from 3.1.0 to 3.1.1 #280. Thanks to Dependabot.
+* Bump commons-parent from 52 to 56 #264, #288, #298. Thanks to Gary Gregory.
+* Bump checkstyle from 8.44 to 9.2.1 #180, #190, #194, #202, #207. Thanks to Dependabot.
+* Bump junit-jupiter from 5.8.0-M1 to 5.9.1 #179, #186, #201, #244, #263. Thanks to Dependabot.
+* Bump jmh-core from 1.32 to 1.36 #176, #208, #229, #285. Thanks to Dependabot.
+* Bump jmh-generator-annprocess from 1.32 to 1.36 #175, #206, #226, #283. Thanks to Dependabot.
+* Bump mockito-core from 3.11.2 to 4.11.0 #187, #197, #204, #212, #230, #237, #251, #259, #284, #292, #297. Thanks to Dependabot, Gary Gregory.
+* Bump maven-pmd-plugin from 3.14.0 to 3.19.0 #184, #219, #238, #254, #258. Thanks to Dependabot.
+* Bump pmd from 6.36.0 to 6.52.0 #173, #189, #193, #199, #227, #233, #214, #236, #240, #247, #255, #273. Thanks to Dependabot, Gary Gregory.
+* Bump opencsv from 5.5.1 to 5.7.1 #182, #221, #260, #281. Thanks to Gary Gregory.
+* Bump spotbugs-maven-plugin from 4.3.0 to 4.7.3.0 #192, #198, #203, #211, #225, #234, #242, #245, #261, #275, #282. Thanks to Dependabot.
+* Bump com.github.spotbugs:spotbugs from 4.5.3 to 4.7.2. Thanks to Gary Gregory.
+* Bump h2 from 1.4.200 to 2.1.214 #200, #205, #213, #239. Thanks to Dependabot.
+* Bump maven-javadoc-plugin from 3.3.0 to 3.4.1. Thanks to Gary Gregory.
+* Bump biz.aQute.bnd:biz.aQute.bndlib from 5.3.0 to 6.3.1. Thanks to Gary Gregory.
+* Bump jacoco-maven-plugin from 0.8.7 to 0.8.8. Thanks to Gary Gregory.
+* Bump japicmp-maven-plugin from 0.15.3 to 0.16.0. Thanks to Gary Gregory.
+* Bump maven-checkstyle-plugin from 3.1.2 to 3.2.0 #253. Thanks to Dependabot.
+
+Removed:
+* Serialization in CSVFormat is not supported from one version to the next.
+
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
+
+For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons CSV website:
+
+https://commons.apache.org/proper/commons-csv/
+
+Download page: https://commons.apache.org/proper/commons-csv/download_csv.cgi
+
+Have fun!
+-Apache Commons CSV team
+
+------------------------------------------------------------------------------
+
+Apache Commons CSV 1.9.0 Release Notes
+--------------------------------------
+
+This document contains the release notes for the 1.9.0 version of Apache Commons CSV.
+Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
+
+Commons CSV requires at least Java 8.
+
+The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
+
+Feature and bug fix release (Java 8 or above)
+
+Changes in this version include:
+
+New Features
+------------
+
+* CSV-275: Make CSVRecord#toList() public. Thanks to Michael Wyraz, Gary Gregory.
+* Add CSVRecord#stream(). Thanks to Gary Gregory.
+* Add CSVParser#stream(). Thanks to Gary Gregory.
+* CSV-184: Make the method CSVRecord.putIn(Map) public. Thanks to Gaurav Agarwal, M. Steiger, Gary Gregory.
+* Add test cases for CSVRecord with get(Enum) and toString. #54. Thanks to dota17.
+* Add and use CSVFormat.Builder, deprecated CSVFormat#with methods, based on #73. Thanks to Gary Gregory, dota17.
+* CSV-206: Add support for String delimiters #76. Thanks to Gary Gregory, dota17.
+
+Fixed Bugs
+----------
+
+* Replace FindBugs with SpotBugs #56. Thanks to Amey Jadiye.
+* Javadoc typo in CSVFormat let's -> lets #57. Thanks to Chen.
+* CSV-259: CSVFormat.printWithEscapes throws StringIndexOutOfBoundsException when value is Reader #61. Thanks to Chen.
+* Improve CSVFormat test coverage #63. Thanks to Chen.
+* Fix CSVFileParserTest.java to allow for a null return value from record.getComment() #62. Thanks to Chen.
+* Improve test coverage in CSVFormatTest #65. Thanks to Chen.
+* Removed invalid Javadoc markup for CSVFormat EXCEL #64. Thanks to Chen.
+* Improve CSVRecord and CSVPrinter code coverage #66. Thanks to Chen.
+* Improve lexer and token coverage #67. Thanks to Chen.
+* CSV-211: CSVFormat.format trims last delimiter if the delimiter is a white space #71. Thanks to Alpesh Kulkarni, Chen.
+* Replace org.apache.commons.csv.Assertions.notNull() with Objects.requireNonNull(). Thanks to Gary Gregory.
+* CSV-149: Line number is not proper at EOF. Thanks to Kranthi, Gary Gregory, Brent Worden, dota17.
+* CSV-195: Parser iterates over the last CSV Record twice. Thanks to Rodolfo Duldulao, Rodolfo Duldulao, Michael Vitz, dota17.
+* CSV-267: Minor improvements #126, #127, #130. Thanks to Arturo Bernal.
+* CSV-123: Add possibility to use ResultSet header meta data as CSV header #11. Thanks to Emmanuel Bourg, Benedikt Ritter, shivakrishnaah, Gary Gregory.
+* CSV-148: Add test cases for withIgnoreSurroundingSpaces() and withTrim() #70. Thanks to dota17.
+* Update CSVParser.parse(File, Charset, CSVFormat) from IO to NIO. Thanks to Gary Gregory.
+* CSV-271: Missing separator with print(object) followed by printRecord(Object[]) #157. Thanks to Amar Prakash Pandey.
+* CSV-158: Fix EOL checking for read array in ExtendedBufferedReader #5. Thanks to Alexander Bondarev, Benedikt Ritter, Gary Gregory, Chen.
+* CSV-263: Print from Reader with embedded quotes generates incorrect output #78. Thanks to Jason A. Guild, Gary Gregory.
+* Replace JUnit assert by simpler but equivalent calls. #159. Thanks to Arturo Bernal.
+* Update gitignore to ignore idea and vscode #160. Thanks to Seth Falco.
+* CSV-281: Update CSVBenchmark #165. Thanks to belugabehr.
+* CSV-283: Remove Whitespace Check Determines Delimiter Twice #167. Thanks to belugabehr.
+* CSV-283: Document and Automate CSV Benchmark Harness #166. Thanks to belugabehr.
+* CSV-279: Optimize Lexer Delimiter Check for One Character Delimiter #163. Thanks to belugabehr.
+* SpotBugs Error: Medium: org.apache.commons.csv.CSVParser.getHeaderNames() may expose internal representation by returning CSVParser.headerNames [org.apache.commons.csv.CSVParser] At CSVParser.java:[line 599] EI_EXPOSE_REP. Thanks to Gary Gregory.
+* SpotBugs Error: Medium: new org.apache.commons.csv.CSVParser(Reader, CSVFormat, long, long) may expose internal representation by storing an externally mutable object into CSVParser.format [org.apache.commons.csv.CSVParser] At CSVParser.java:[line 433] EI_EXPOSE_REP2. Thanks to Gary Gregory.
+* SpotBugs Error: Medium: new org.apache.commons.csv.CSVParser(Reader, CSVFormat, long, long) may expose internal representation by storing an externally mutable object into CSVParser.headerMap [org.apache.commons.csv.CSVParser] At CSVParser.java:[line 437] EI_EXPOSE_REP2. Thanks to Gary Gregory.
+* SpotBugs Error: Medium: new org.apache.commons.csv.CSVParser(Reader, CSVFormat, long, long) may expose internal representation by storing an externally mutable object into CSVParser.headerNames [org.apache.commons.csv.CSVParser] At CSVParser.java:[line 438] EI_EXPOSE_REP2. Thanks to Gary Gregory.
+* SpotBugs Error: Medium: new org.apache.commons.csv.CSVPrinter(Appendable, CSVFormat) may expose internal representation by storing an externally mutable object into CSVPrinter.format [org.apache.commons.csv.CSVPrinter] At CSVPrinter.java:[line 100] EI_EXPOSE_REP2. Thanks to Gary Gregory.
+* CSV-284: Formalize PerformanceTest #168. Thanks to belugabehr.
+* CSV-278: Reuse Buffers in Lexer for Delimiter Detection #162. Thanks to belugabehr.
+* CSV-286: Cleanup and Document Performance Test Harness #170. Thanks to belugabehr.
+* CSV-265: Update buffer position when reading line comment #120. Thanks to belugabehr.
+
+Changes
+-------
+
+* Update org.junit.jupiter:junit-jupiter from 5.6.0 to 5.7.0, #84 #109 Thanks to Gary Gregory.
+* Update tests from Apache Commons Lang 3.9 to 3.12.0. Thanks to Gary Gregory.
+* Update tests from commons-io:commons-io 2.6 to 2.11.0, #108. Thanks to Gary Gregory.
+* Bump actions/checkout from v1 to v2.3.4, #79, #92, #121. Thanks to Dependabot.
+* Bump commons-parent from 50 to 51 #80. Thanks to Dependabot.
+* Bump tests from opencsv from 3.1 to 5.5.1 #81, #137, #158. Thanks to Dependabot, Gary Gregory.
+* Update tests from super-csv from 2.2.1 to 2.4.0 #86. Thanks to Gary Gregory.
+* Bump build actions/setup-java from v1.4.0 to v2, #101, #113. Thanks to Dependabot, Gary Gregory.
+* Bump maven-pmd-plugin from 3.13.0 to 3.14.0 #122. Thanks to Dependabot.
+* Bump tests from org.mockito:mockito-core 3.2.4 -> 3.11.2; #88, #107, #110, #123, #128, #129, #156. Thanks to Gary Gregory, Dependabot.
+* Bump actions/cache from v2 to v2.1.6 #132, #153. Thanks to Dependabot.
+* Bump maven-checkstyle-plugin from 3.0.0 to 3.1.2 #131. Thanks to Gary Gregory, Dependabot.
+* Bump checkstyle from 8.29 to 8.44. Thanks to Gary Gregory.
+* Bump junit-jupiter from 5.7.0 to 5.8.0-M1 #133, #149. Thanks to Dependabot, Gary Gregory.
+* Bump commons.jacoco.version from 0.8.5 to 0.8.7 (Java 16). Thanks to Dependabot.
+* Bump commons.spotbugs.version from 4.0.4 to 4.3.0 (Java 16). Thanks to Dependabot.
+* Bump maven-javadoc-plugin from 3.2.0 to 3.3.0. Thanks to Gary Gregory.
+* Bump jmh-generator-annprocess from 1.5.2 to 1.32 #151. Thanks to Dependabot.
+* Bump PMD core from 6.29.0 to 6.36.0. Thanks to Dependabot.
+* Bump biz.aQute.bnd:biz.aQute.bndlib from 5.1.2 to 5.3.0. Thanks to Dependabot.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
+
+For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons CSV website:
+
+https://commons.apache.org/proper/commons-csv/
+
+Download page: https://commons.apache.org/proper/commons-csv/download_csv.cgi
+
+Have fun!
+-Apache Commons CSV team
+
+------------------------------------------------------------------------------
+
+Apache Commons CSV 1.8 Release Notes
+------------------------------------
+
+This document contains the release notes for the 1.8 version of Apache Commons CSV.
+Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
+
+Commons CSV requires at least Java 8.
+
+This release fixes serialization compatibility of CSVRecord with versions 1.0 to 1.6. New fields added since
+1.7 are not serialized. Support for Serializable is scheduled to be removed in version 2.0.
+
+Changes in this version include:
+
+New Features
+------------==
+
+* CSV-255: Add CSVRecord.isSet(int) method #52. Thanks to 0x100.
+
+Fixed Bugs
+----------==
+
+* CSV-135: Char escape doesn't work properly with quoting. Thanks to Mateusz Zakarczemny.
+* CSV-244: Test case failures following CSVFormat#equals() update.
+* CSV-243: CSVFormat withTrim() and withIgnoreSurroundingSpaces() need better docs.
+* CSV-242: CSVFormat equals() and hashCode() don't use all fields.
+* CSV-241: CSVFormat#validate() does not account for allowDuplicateHeaderNames #43. Thanks to LuckyIlam, Gary Gregory.
+* CSV-245: Post 1.7 release fixes. Thanks to Alex Herbert.
+* CSV-252: Upgrade test framework to JUnit 5 Jupiter #49, #50. Thanks to Alex Herbert.
+* CSV-247: A single empty header is allowed when not allowing empty column headers. #47. Thanks to Alex Herbert, Gary Gregory.
+* CSV-248: CSVRecord is not Serializable. Thanks to Alex Herbert.
+* Use test scope for supercsv #48. Thanks to Alex Herbert.
+
+Changes
+-------==
+
+* Update tests from H2 1.4.199 to 1.4.200. Thanks to Gary Gregory.
+* Update tests from Hamcrest 2.1 to 2.2. Thanks to Gary Gregory.
+* Update tests from Mockito 3.1.0 to 3.2.4. Thanks to Gary Gregory.
+* Fix typos in site and test #53. Thanks to Chen.
+* Fix typo performance test #55. Thanks to Chen.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
+
+For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons CSV website:
+
+https://commons.apache.org/proper/commons-csv/
+
+Download page: https://commons.apache.org/proper/commons-csv/download_csv.cgi
+
+Have fun!
+-Apache Commons CSV team
+
+------------------------------------------------------------------------------
+
+Apache Commons CSV 1.7 Release Notes
+------------------------------------
+
+This document contains the release notes for the 1.7 version of Apache Commons CSV.
+Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
+
+The Apache Commons CSV library provides a simple interface for reading and writing
+CSV files of various types.
+
+Feature and bug fix release (Java 8 or above)
+
+Changes in this version include:
+
+New Features
+------------==
+
+* CSV-233: Add predefined CSVFormats for printing MongoDB CSV and TSV. Thanks to Gary Gregory.
+* CSV-234: Add support for java.sql.Clob. Thanks to Roberto Benedetti, Gary Gregory.
+* CSV-239: Cannot get headers in column order from CSVRecord. Thanks to Gary Gregory, Dave Moten.
+
+Fixed Bugs
+----------==
+
+* CSV-208: Fix escape character for POSTGRESQL_TEXT and POSTGRESQL_CSV formats. Thanks to Jurrie Overgoor.
+* CSV-232: Site link "Source Repository" does not work. Thanks to Jurrie Overgoor, Gary Gregory.
+* CSV-238: Escape quotes in CLOBs #39. Thanks to Stephen Olander-Waters.
+
+Changes
+-------==
+
+* CSV-237: Update to Java 8. Thanks to Gary Gregory.
+* Update tests from H2 1.4.198 to 1.4.199. Thanks to Gary Gregory.
+
+
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
+
+For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons CSV website:
+
+https://commons.apache.org/proper/commons-csv/
+
+Download it from https://commons.apache.org/proper/commons-csv/download_csv.cgi
+
+Have fun!
+-Apache Commons CSV team
+
+------------------------------------------------------------------------------
+
+Apache Commons CSV 1.6 Release Notes
+------------------------------------
This document contains the release notes for the 1.6 version of
Apache Commons CSV. Commons CSV reads and writes files in variations of the
@@ -18,33 +585,33 @@ Feature and bug fix release.
Changes in this version include:
-NEW FEATURES
-==============
+New Features
+------------==
-o CSV-217: Add autoFlush option for CsvPrinter. PR #24.
+* CSV-217: Add autoFlush option for CsvPrinter. PR #24.
Thanks to Korolyov Alexei.
-o CSV-220: Add API org.apache.commons.csv.CSVFormat.withSystemRecordSeparator().
+* CSV-220: Add API org.apache.commons.csv.CSVFormat.withSystemRecordSeparator().
Thanks to Gary Gregory.
-FIXED BUGS
-============
+Fixed Bugs
+----------==
-o CSV-219: The behavior of quote char using is not similar as Excel does when
+* CSV-219: The behavior of quote char using is not similar as Excel does when
the first string contains CJK char(s). Thanks to Zhang Hongda.
-o CSV-172: Don't quote cells just because they have UTF-8 encoded characters.
+* CSV-172: Don't quote cells just because they have UTF-8 encoded characters.
Thanks to Andrew Pennebaker.
-o CSV-223: Inconsistency between Javadoc of CSVFormat DEFAULT EXCEL.
+* CSV-223: Inconsistency between Javadoc of CSVFormat DEFAULT EXCEL.
Thanks to Samuel Martin.
-o CSV-209: Create CSVFormat.ORACLE preset. Thanks to Gary Gregory.
-o CSV-224: Some multi-iterator parsing peek sequences incorrectly consume
+* CSV-209: Create CSVFormat.ORACLE preset. Thanks to Gary Gregory.
+* CSV-224: Some multi-iterator parsing peek sequences incorrectly consume
elements. Thanks to David Warshaw.
-o CSV-225: Parse method should avoid creating a redundant BufferedReader.
+* CSV-225: Parse method should avoid creating a redundant BufferedReader.
Thanks to Anson Schwabecher.
-CHANGES
-=========
+Changes
+-------==
-o CSV-231: Add more documentation to CSVPrinter.
+* CSV-231: Add more documentation to CSVPrinter.
Have fun!
@@ -52,12 +619,8 @@ Have fun!
------------------------------------------------------------------------------
- Apache Commons CSV
- Version 1.5
- Release Notes
-
-
-INTRODUCTION:
+Apache Commons CSV 1.5 Release Notes
+------------------------------------
This document contains the release notes for the 1.5 version of Apache Commons CSV.
Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
@@ -71,50 +634,46 @@ Feature and bug fix release
Changes in this version include:
-NEW FEATURES
-==============
+New Features
+------------==
-o CSV-189: CSVParser: Add factory method accepting InputStream. Thanks to Peter Holzwarth, Gary Gregory.
-o CSV-190: Add convenience API CSVFormat.print(File, Charset). Thanks to Gary Gregory.
-o CSV-191: Add convenience API CSVFormat.print(Path, Charset). Thanks to Gary Gregory.
-o CSV-192: Add convenience API CSVParser.parse(Path, Charset, CSVFormat). Thanks to Gary Gregory.
-o CSV-205: Add convenience API CSVFormat#printer() to print to System.out. Thanks to Gary Gregory.
-o CSV-207: Provide a CSV Format for printing PostgreSQL CSV and Text formats. Thanks to Gary Gregory.
-o CSV-214: Adding a placeholder in the Lexer and CSV parser to store the end-of-line string. Thanks to Nitin Mahendru, Gary Gregory.
+* CSV-189: CSVParser: Add factory method accepting InputStream. Thanks to Peter Holzwarth, Gary Gregory.
+* CSV-190: Add convenience API CSVFormat.print(File, Charset). Thanks to Gary Gregory.
+* CSV-191: Add convenience API CSVFormat.print(Path, Charset). Thanks to Gary Gregory.
+* CSV-192: Add convenience API CSVParser.parse(Path, Charset, CSVFormat). Thanks to Gary Gregory.
+* CSV-205: Add convenience API CSVFormat#printer() to print to System.out. Thanks to Gary Gregory.
+* CSV-207: Provide a CSV Format for printing PostgreSQL CSV and Text formats. Thanks to Gary Gregory.
+* CSV-214: Adding a placeholder in the Lexer and CSV parser to store the end-of-line string. Thanks to Nitin Mahendru, Gary Gregory.
-FIXED BUGS
-============
+Fixed Bugs
+----------==
-o CSV-203: withNullString value is printed without quotes when QuoteMode.ALL is specified; add QuoteMode.ALL_NON_NULL. PR #17. Thanks to Richard Wheeldon, Kai Paroth.
-o CSV-194: Fix outdated comments about FileReader in CSVParser #13. Thanks to Marc Prud'hommeaux.
-o CSV-193: Fix incorrect method name 'withFirstRowAsHeader' in user guide. Thanks to Matthias Wiehl.
-o CSV-171: Negative numeric values in the first column are always quoted in minimal mode. Thanks to Gary Gregory, Michael Graessle, Adrian Bridgett.
+* CSV-203: withNullString value is printed without quotes when QuoteMode.ALL is specified; add QuoteMode.ALL_NON_NULL. PR #17. Thanks to Richard Wheeldon, Kai Paroth.
+* CSV-194: Fix outdated comments about FileReader in CSVParser #13. Thanks to Marc Prud'hommeaux.
+* CSV-193: Fix incorrect method name 'withFirstRowAsHeader' in user guide. Thanks to Matthias Wiehl.
+* CSV-171: Negative numeric values in the first column are always quoted in minimal mode. Thanks to Gary Gregory, Michael Graessle, Adrian Bridgett.
-CHANGES
-=========
+Changes
+-------==
-o CSV-187: Update platform requirement from Java 6 to 7. Thanks to Gary Gregory.
-o CSV-201: Do not use RuntimeException in CSVParser.iterator().new Iterator() {...}.getNextRecord(). Thanks to Benedikt Ritter, Gary Gregory.
+* CSV-187: Update platform requirement from Java 6 to 7. Thanks to Gary Gregory.
+* CSV-201: Do not use RuntimeException in CSVParser.iterator().new Iterator() {...}.getNextRecord(). Thanks to Benedikt Ritter, Gary Gregory.
-Historical list of changes: http://commons.apache.org/proper/commons-csv/changes-report.html
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
-patches, or suggestions for improvement, see the Apache Apache Commons CSV website:
+patches, or suggestions for improvement, see the Apache Commons CSV website:
-http://commons.apache.org/proper/commons-csv/
+https://commons.apache.org/proper/commons-csv/
Have fun!
-Apache Commons CSV team
------------------------------------------------------------------------------
- Apache Commons CSV
- Version 1.4
- Release Notes
-
-
-INTRODUCTION:
+Apache Commons CSV 1.4 Release Notes
+------------------------------------
This document contains the release notes for the 1.4 version of Apache Commons CSV.
Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
@@ -128,37 +687,33 @@ Feature and bug fix release
Changes in this version include:
-NEW FEATURES
-==============
+New Features
+------------==
-o CSV-182: Allow some printing operations directly from CSVFormat. Thanks to Gary Gregory.
+* CSV-182: Allow some printing operations directly from CSVFormat. Thanks to Gary Gregory.
-CHANGES
-=========
+Changes
+-------==
-o CSV-181: Make CSVPrinter.print(Object) GC-free. Thanks to Gary Gregory.
-o CSV-183: Drop ferc.gov tests.
+* CSV-181: Make CSVPrinter.print(Object) GC-free. Thanks to Gary Gregory.
+* CSV-183: Drop ferc.gov tests.
-Historical list of changes: http://commons.apache.org/proper/commons-csv/changes-report.html
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
-patches, or suggestions for improvement, see the Apache Apache Commons CSV website:
+patches, or suggestions for improvement, see the Apache Commons CSV website:
-http://commons.apache.org/proper/commons-csv/
+https://commons.apache.org/proper/commons-csv/
Have fun!
-Apache Commons CSV team
------------------------------------------------------------------------------
- Apache Commons CSV
- Version 1.3
- Release Notes
-
-
-INTRODUCTION:
+Apache Commons CSV 1.3 Release Notes
+------------------------------------
This document contains the release notes for the 1.3 version of Apache Commons CSV.
Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
@@ -172,29 +727,29 @@ Feature and bug fix release.
Changes in this version include:
-NEW FEATURES
-==============
+New Features
+------------==
-o CSV-179: Add shortcut method for using first record as header to CSVFormat.
-o CSV-180: Add withHeader(Class? extends Enum>) to CSVFormat.
-o CSV-159: Add IgnoreCase option for accessing header names. Thanks to Yamil Medina.
-o CSV-169: The null string should be case-sensitive when reading records. Thanks to Gary Gregory.
-o CSV-175: Support for ignoring trailing delimiter. Thanks to Gary Gregory, Chris Jones.
-o CSV-177: Support trimming leading and trailing blanks. Thanks to Gary Gregory.
-o CSV-178: Create default formats for Informix UNLOAD and UNLOAD CSV. Thanks to Gary Gregory.
+* CSV-179: Add shortcut method for using first record as header to CSVFormat.
+* CSV-180: Add withHeader(Class? extends Enum>) to CSVFormat.
+* CSV-159: Add IgnoreCase option for accessing header names. Thanks to Yamil Medina.
+* CSV-169: The null string should be case-sensitive when reading records. Thanks to Gary Gregory.
+* CSV-175: Support for ignoring trailing delimiter. Thanks to Gary Gregory, Chris Jones.
+* CSV-177: Support trimming leading and trailing blanks. Thanks to Gary Gregory.
+* CSV-178: Create default formats for Informix UNLOAD and UNLOAD CSV. Thanks to Gary Gregory.
-FIXED BUGS
-============
+Fixed Bugs
+----------==
-o CSV-168: CSVFormat.nullString should not be escaped. Thanks to Gary Gregory, cornel creanga.
-o CSV-170: CSVFormat.MYSQL nullString should be "\N". Thanks to Gary Gregory, cornel creanga.
-o CSV-161: Fix Javadoc to say CSVFormat with() methods return a new CSVFormat. Thanks to Gary Gregory, Kristof Meixner, Emmanuel Bourg.
+* CSV-168: CSVFormat.nullString should not be escaped. Thanks to Gary Gregory, cornel creanga.
+* CSV-170: CSVFormat.MYSQL nullString should be "\N". Thanks to Gary Gregory, cornel creanga.
+* CSV-161: Fix Javadoc to say CSVFormat with() methods return a new CSVFormat. Thanks to Gary Gregory, Kristof Meixner, Emmanuel Bourg.
-CHANGES
-============
+Changes
+-------=====
-o CSV-167: Comment line hides next record; update Javadoc to make behaviour clear. Thanks to Rene.
-o CSV-153: CSVPrinter doesn't skip creation of header record if skipHeaderRecord is set to true. Thanks to Wren.
+* CSV-167: Comment line hides next record; update Javadoc to make behavior clear. Thanks to Rene.
+* CSV-153: CSVPrinter doesn't skip creation of header record if skipHeaderRecord is set to true. Thanks to Wren.
Have fun!
@@ -202,12 +757,8 @@ Have fun!
------------------------------------------------------------------------------
- Apache Commons CSV
- Version 1.2
- Release Notes
-
-
-INTRODUCTION:
+Apache Commons CSV 1.2 Release Notes
+------------------------------------
This document contains the release notes for the 1.2 version of Apache Commons CSV.
Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
@@ -221,36 +772,32 @@ Feature and bug fix release
Changes in this version include:
-NEW FEATURES
-==============
+New Features
+------------==
-o CSV-157: Add enum CSVFormat.Predefined that contains the default CSVFormat values.
+* CSV-157: Add enum CSVFormat.Predefined that contains the default CSVFormat values.
-FIXED BUGS
-============
+Fixed Bugs
+----------==
-o CSV-145: CSVFormat.with* methods clear the header comments. Thanks to Frank Ulbricht.
-o CSV-156: Incorrect Javadoc on QuoteMode.NONE. Thanks to Jason Steenstra-Pickens.
+* CSV-145: CSVFormat.with* methods clear the header comments. Thanks to Frank Ulbricht.
+* CSV-156: Incorrect Javadoc on QuoteMode.NONE. Thanks to Jason Steenstra-Pickens.
-Historical list of changes: http://commons.apache.org/proper/commons-csv/changes-report.html
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
-patches, or suggestions for improvement, see the Apache Apache Commons CSV website:
+patches, or suggestions for improvement, see the Apache Commons CSV website:
-http://commons.apache.org/proper/commons-csv/
+https://commons.apache.org/proper/commons-csv/
Have fun!
-Apache Commons CSV team
------------------------------------------------------------------------------
- Apache Commons CSV
- Version 1.1
- Release Notes
-
-
-INTRODUCTION:
+Apache Commons CSV 1.1 Release Notes
+------------------------------------
This document contains the release notes for the 1.1 version of Apache Commons CSV.
Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
@@ -265,38 +812,34 @@ This is our second release.
Changes in this version include:
New features:
-o [CSV-129] Add CSVFormat#with 0-arg methods matching boolean arg methods.
-o [CSV-131] Save positions of records to enable random access. Thanks to Holger Stratmann.
-o [CSV-139] CSVPrinter.printRecord(ResultSet) with metadata.
+* [CSV-129] Add CSVFormat#with 0-arg methods matching boolean arg methods.
+* [CSV-131] Save positions of records to enable random access. Thanks to Holger Stratmann.
+* [CSV-139] CSVPrinter.printRecord(ResultSet) with metadata.
Fixed Bugs:
-o [CSV-140] QuoteMode.NON_NUMERIC doesn't work with CSVPrinter.printRecords(ResultSet). Thanks to Damjan Jovanovic.
-o [CSV-130] CSVFormat#withHeader doesn't work well with #printComment, add withHeaderComments(String...). Thanks to Sergei Lebedev.
-o [CSV-128] CSVFormat.EXCEL should ignore empty header names.
-o [CSV-132] Incorrect Javadoc referencing org.apache.commons.csv.CSVFormat withQuote(). Thanks to Sascha Szott.
+* [CSV-140] QuoteMode.NON_NUMERIC doesn't work with CSVPrinter.printRecords(ResultSet). Thanks to Damjan Jovanovic.
+* [CSV-130] CSVFormat#withHeader doesn't work well with #printComment, add withHeaderComments(String...). Thanks to Sergei Lebedev.
+* [CSV-128] CSVFormat.EXCEL should ignore empty header names.
+* [CSV-132] Incorrect Javadoc referencing org.apache.commons.csv.CSVFormat withQuote(). Thanks to Sascha Szott.
Changes:
-o [CSV-124] Improve toString() implementation of CSVRecord. Thanks to Kalyan.
-o [CSV-134] Unified parameter validation. Thanks to wu wen.
+* [CSV-124] Improve toString() implementation of CSVRecord. Thanks to Kalyan.
+* [CSV-134] Unified parameter validation. Thanks to wu wen.
-Historical list of changes: http://commons.apache.org/proper/commons-csv/changes-report.html
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
-patches, or suggestions for improvement, see the Apache Apache Commons CSV website:
+patches, or suggestions for improvement, see the Apache Commons CSV website:
-http://commons.apache.org/proper/commons-csv/
+https://commons.apache.org/proper/commons-csv/
Have fun!
-Apache Commons CSV team
-------------------------------------------------------------------------------
- Apache Commons CSV
- Version 1.0
- Release Notes
-
-
-INTRODUCTION:
+Apache Commons CSV 1.0 Release Notes
+------------------------------------
This document contains the release notes for the 1.0 version of Apache Commons CSV.
Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
@@ -310,76 +853,76 @@ First release
Changes in this version include:
-NEW FEATURES
-============
+New Features
+------------
-o CSV-121: IllegalArgumentException thrown when the header contains duplicate names when the column names are empty.
+* CSV-121: IllegalArgumentException thrown when the header contains duplicate names when the column names are empty.
Thanks to Sebastian Hardt.
-o CSV-120: CSVFormat#withHeader doesn't work with CSVPrinter Thanks to Sergei Lebedev.
-o CSV-119: CSVFormat is missing a print(...) method Thanks to Sergei Lebedev.
-o CSV-105: Add Map conversion API to CSVRecord
-o CSV-52: Keep track of record number
-o CSV-92: Need a way to extract parsed headers, e.g. for use in formatting
+* CSV-120: CSVFormat#withHeader doesn't work with CSVPrinter Thanks to Sergei Lebedev.
+* CSV-119: CSVFormat is missing a print(...) method Thanks to Sergei Lebedev.
+* CSV-105: Add Map conversion API to CSVRecord
+* CSV-52: Keep track of record number
+* CSV-92: Need a way to extract parsed headers, e.g. for use in formatting
output
-o CSV-65: Header support
-o CSV-48: Predefined format for MYSQL
+* CSV-65: Header support
+* CSV-48: Predefined format for MYSQL
-FIXED BUGS
-==========
+Fixed Bugs
+----------
-o CSV-125: No longer works with Java 6
-o CSV-122: NullPointerException when empty header string and and null string of "".
+* CSV-125: No longer works with Java 6
+* CSV-122: NullPointerException when empty header string and null string of "".
Thanks to Mike Lewis.
-o CSV-118: CSVRecord.toMap() throws NPE on formats with no
+* CSV-118: CSVRecord.toMap() throws NPE on formats with no
headers. Thanks to Enrique Lara.
-o CSV-113: Check whether ISE/IAE are being used appropriately
-o CSV-114: CSVFormat constructor should reject a header array with duplicate
+* CSV-113: Check whether ISE/IAE are being used appropriately
+* CSV-114: CSVFormat constructor should reject a header array with duplicate
entries
-o CSV-112: HeaderMap is inconsistent when it is parsed from an input with
+* CSV-112: HeaderMap is inconsistent when it is parsed from an input with
duplicate columns names
-o CSV-111: CSVRecord.toMap() fails if row length shorter than header length
-o CSV-106: CSVFormat.format allways append null
-o CSV-100: CSVParser: getHeaderMap throws NPE
-o CSV-53: CSVRecord does not verify that the length of the header mapping
+* CSV-111: CSVRecord.toMap() fails if row length shorter than header length
+* CSV-106: CSVFormat.format allways append null
+* CSV-100: CSVParser: getHeaderMap throws NPE
+* CSV-53: CSVRecord does not verify that the length of the header mapping
matches the number of values
-o CSV-54: Confusing semantic of the ignore leading/trailing spaces parameters
-o CSV-34: CSVFormat describes itself as immutable, but it is not - in
+* CSV-54: Confusing semantic of the ignore leading/trailing spaces parameters
+* CSV-34: CSVFormat describes itself as immutable, but it is not - in
particular it is not thread-safe
-o CSV-36: Endless loops in CSV parser
-o CSV-13: NullPointerException in CSVPrinter.print()/println()
-o CSV-23: Excel strategy uses wrong separator
-
-CHANGES
-=======
-
-o CSV-117: Validate format parameters in constructor
-o CSV-42: Lots of possible changes Thanks to Bob Smith.
-o CSV-78: Use Character instead of char for char fields except delimiter
-o CSV-99: Revert Builder implementation in CSVFormat
-o CSV-93: Allow the handling of NULL values
-o CSV-68: Use the Builder pattern for CSVFormat
-o CSV-84: Clarify comment handling
-o CSV-25: CSVParser.nextValue() seems pointless
-o CSV-97: Allow the String value for null to be customized for the CSV
+* CSV-36: Endless loops in CSV parser
+* CSV-13: NullPointerException in CSVPrinter.print()/println()
+* CSV-23: Excel strategy uses wrong separator
+
+Changes
+-------
+
+* CSV-117: Validate format parameters in constructor
+* CSV-42: Lots of possible changes Thanks to Bob Smith.
+* CSV-78: Use Character instead of char for char fields except delimiter
+* CSV-99: Revert Builder implementation in CSVFormat
+* CSV-93: Allow the handling of NULL values
+* CSV-68: Use the Builder pattern for CSVFormat
+* CSV-84: Clarify comment handling
+* CSV-25: CSVParser.nextValue() seems pointless
+* CSV-97: Allow the String value for null to be customized for the CSV
printer
-o CSV-88: Not possible to create a CSVFormat from scratch
-o CSV-94: Lexer should only use char fields
-o CSV-71: Add convenience methods to CSVLexer
-o CSV-59: Is CharBuffer really needed, now that StringBuilder is available?
-o CSV-55: Replace while(true)-loop in CSVParser.getRecord with do-while-loop
-o CSV-45: CSVPrinter overhaul
-o CSV-49: CSVStrategy has modifiable public static variables Thanks to Bob Smith.
-o CSV-46: Reduce visibility of methods in internal classes
-o CSV-26: ExtendedBufferedReader does too much
-o CSV-27: Decide whether to keep the csv.writer subpackage
+* CSV-88: Not possible to create a CSVFormat from scratch
+* CSV-94: Lexer should only use char fields
+* CSV-71: Add convenience methods to CSVLexer
+* CSV-59: Is CharBuffer really needed, now that StringBuilder is available?
+* CSV-55: Replace while(true)-loop in CSVParser.getRecord with do-while-loop
+* CSV-45: CSVPrinter overhaul
+* CSV-49: CSVStrategy has modifiable public static variables Thanks to Bob Smith.
+* CSV-46: Reduce visibility of methods in internal classes
+* CSV-26: ExtendedBufferedReader does too much
+* CSV-27: Decide whether to keep the csv.writer subpackage
-Historical list of changes: http://commons.apache.org/proper/commons-csv/changes-report.html
+Historical list of changes: https://commons.apache.org/proper/commons-csv/changes.html
For complete information on Apache Commons CSV, including instructions on how to submit bug reports,
-patches, or suggestions for improvement, see the Apache Apache Commons CSV website:
+patches, or suggestions for improvement, see the Apache Commons CSV website:
-http://commons.apache.org/proper/commons-csv/
+https://commons.apache.org/proper/commons-csv/
Have fun!
-Apache Commons CSV team
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000000..744d4cddbb
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,17 @@
+
+The Apache Commons security page is [https://commons.apache.org/security.html](https://commons.apache.org/security.html).
diff --git a/benchmark-prereq.sh b/benchmark-prereq.sh
new file mode 100755
index 0000000000..bd1db91821
--- /dev/null
+++ b/benchmark-prereq.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+##
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+wget -P /tmp https://kasparov.skife.org/csv/csv-1.0.jar
+mvn -V install:install-file -Dfile=/tmp/csv-1.0.jar -DgroupId=org.skife.kasparov -DartifactId=csv -Dversion=1.0 -Dpackaging=jar
diff --git a/checkstyle.xml b/checkstyle.xml
deleted file mode 100644
index 47fbf3aa17..0000000000
--- a/checkstyle.xml
+++ /dev/null
@@ -1,69 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/pom.xml b/pom.xml
index fc7fa16b91..8cb13ed7c2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,533 +1,525 @@
-
-
-
- 4.0.0
-
- org.apache.commons
- commons-parent
- 47
-
- commons-csv
- 1.7-SNAPSHOT
- Apache Commons CSV
- http://commons.apache.org/proper/commons-csv/
-
-The Apache Commons CSV library provides a simple interface for reading and writing
-CSV files of various types.
-
-
-
-
- junit
- junit
- 4.12
- test
-
-
- org.mockito
- mockito-all
- 1.10.19
- test
-
-
- commons-io
- commons-io
- 2.6
- test
-
-
- org.apache.commons
- commons-lang3
- 3.8.1
- test
-
-
- com.h2database
- h2
- 1.4.199
- test
-
-
-
-
-
- bayard
- Henri Yandell
- bayard@apache.org
- The Apache Software Foundation
-
-
- Martin van den Bemt
- mvdb
- mvdb@apache.org
- The Apache Software Foundation
-
-
- Yonik Seeley
- yonik
- yonik@apache.org
- The Apache Software Foundation
-
-
- Emmanuel Bourg
- ebourg
- ebourg@apache.org
- Apache
-
-
- Gary Gregory
- ggregory
- ggregory@apache.org
- http://www.garygregory.com
-
-
- Benedikt Ritter
- britter
- britter@apache.org
- The Apache Software Foundation
-
-
- Rob Tompkins
- chtompki
- chtompki@apache.org
- The Apache Software Foundation
-
-
-
-
- Bob Smith
-
-
-
-
- scm:git:http://git-wip-us.apache.org/repos/asf/commons-csv.git
- scm:git:https://git-wip-us.apache.org/repos/asf/commons-csv.git
- https://git-wip-us.apache.org/repos/asf?p=commons-csv.git
-
-
-
- jira
- http://issues.apache.org/jira/browse/CSV
-
-
-
-
- apache.website
- Apache Commons Site
- scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-csv/
-
-
-
-
- 1.7
- (Java 8)
-
- RC1
- csv
- org.apache.commons.csv
- CSV
- 12313222
- 2005
- 1.8
- 1.8
-
- UTF-8
- UTF-8
- UTF-8
-
- 3.0.0
- ${basedir}/LICENSE-header.txt
- LICENSE.txt, NOTICE.txt
-
-
- https://svn.apache.org/repos/infra/websites/production/commons/content/proper/${project.artifactId}
-
- org.apache.commons.${commons.componentid}
-
-
-
- clean verify apache-rat:check clirr:check javadoc:javadoc
-
-
-
- org.apache.maven.plugins
- maven-scm-publish-plugin
- 1.1
-
-
- archives/**
-
-
-
-
-
-
-
- maven-compiler-plugin
-
-
- **/*Benchmark*
-
-
-
-
- maven-assembly-plugin
-
-
- src/assembly/bin.xml
- src/assembly/src.xml
-
- gnu
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- **/perf/PerformanceTest.java
-
-
-
-
-
- org.apache.maven.plugins
- maven-checkstyle-plugin
- ${checkstyle.version}
-
- ${basedir}/checkstyle.xml
- false
-
-
-
-
-
-
- org.apache.rat
- apache-rat-plugin
-
-
-
-
- src/test/resources/csv-167/sample1.csv
- src/test/resources/CSV-198/optd_por_public.csv
- src/test/resources/CSV-213/999751170.patch.csv
- src/test/resources/CSVFileParser/bom.csv
- src/test/resources/CSVFileParser/test.csv
- src/test/resources/CSVFileParser/test_default.txt
- src/test/resources/CSVFileParser/test_default_comment.txt
- src/test/resources/CSVFileParser/test_rfc4180.txt
- src/test/resources/CSVFileParser/test_rfc4180_trim.txt
- src/test/resources/CSVFileParser/testCSV85.csv
- src/test/resources/CSVFileParser/testCSV85_default.txt
- src/test/resources/CSVFileParser/testCSV85_ignoreEmpty.txt
-
- src/test/resources/ferc.gov/contract.txt
- src/test/resources/ferc.gov/transaction.txt
-
-
-
-
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-checkstyle-plugin
- ${checkstyle.version}
-
- ${basedir}/checkstyle.xml
- false
-
-
-
-
-
- checkstyle
-
-
-
-
-
- org.apache.maven.plugins
- maven-pmd-plugin
- 3.11.0
-
- ${maven.compiler.target}
-
-
-
- org.codehaus.mojo
- findbugs-maven-plugin
-
-
- org.codehaus.mojo
- taglist-maven-plugin
- 2.4
-
-
-
-
- Needs Work
-
-
- TODO
- exact
-
-
- FIXME
- exact
-
-
- XXX
- exact
-
-
-
-
- Noteable Markers
-
-
- NOTE
- exact
-
-
- NOPMD
- exact
-
-
- NOSONAR
- exact
-
-
-
-
-
-
-
-
-
- org.codehaus.mojo
- javancss-maven-plugin
- 2.1
-
-
-
-
- org.apache.rat
- apache-rat-plugin
- ${commons.rat.version}
-
-
-
- src/test/resources/csv-167/sample1.csv
- src/test/resources/CSV-198/optd_por_public.csv
- src/test/resources/CSV-213/999751170.patch.csv
- src/test/resources/CSVFileParser/bom.csv
- src/test/resources/CSVFileParser/test.csv
- src/test/resources/CSVFileParser/test_default.txt
- src/test/resources/CSVFileParser/test_default_comment.txt
- src/test/resources/CSVFileParser/test_rfc4180.txt
- src/test/resources/CSVFileParser/test_rfc4180_trim.txt
- src/test/resources/CSVFileParser/testCSV85.csv
- src/test/resources/CSVFileParser/testCSV85_default.txt
- src/test/resources/CSVFileParser/testCSV85_ignoreEmpty.txt
- src/test/resources/ferc.gov/contract.txt
- src/test/resources/ferc.gov/transaction.txt
-
-
-
-
-
-
-
-
- setup-checkout
-
-
- site-content
-
-
-
-
-
- org.apache.maven.plugins
- maven-antrun-plugin
- 1.8
-
-
- prepare-checkout
- pre-site
-
- run
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- benchmark
-
-
-
- org.openjdk.jmh
- jmh-core
- 1.5.2
- test
-
-
-
- org.openjdk.jmh
- jmh-generator-annprocess
- 1.5.2
- test
-
-
-
- genjava
- gj-csv
- 1.0
- test
-
-
-
- net.sourceforge.javacsv
- javacsv
- 2.0
- test
-
-
-
- com.opencsv
- opencsv
- 3.1
- test
-
-
-
- net.sf.supercsv
- super-csv
- 2.2.1
-
-
-
-
- org.skife.kasparov
- csv
- 1.0
-
-
-
- org.apache.commons
- commons-lang3
- 3.6
-
-
-
-
- true
- org.apache
-
-
-
-
-
-
- maven-compiler-plugin
-
-
- **/*
-
-
-
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
-
-
- benchmark
- test
-
- exec
-
-
- test
- java
-
- -classpath
-
- org.openjdk.jmh.Main
- -rf
- json
- -rff
- target/jmh-result.json
- ${benchmark}
-
-
-
-
-
-
-
-
-
-
- java9
-
- 9
-
-
-
- true
-
-
-
-
-
+
+
+
+ 4.0.0
+
+ org.apache.commons
+ commons-parent
+ 102
+
+ commons-csv
+ 1.15.0-SNAPSHOT
+ Apache Commons CSV
+ https://commons.apache.org/proper/commons-csv/
+ 2005
+ The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
+
+
+ org.junit.jupiter
+ junit-jupiter
+ test
+
+
+ org.mockito
+ mockito-core
+ ${commons.mockito.version}
+ test
+
+
+ commons-io
+ commons-io
+ ${commons.io.version}
+
+
+ commons-codec
+ commons-codec
+ ${commons.codec.version}
+
+
+ org.apache.commons
+ commons-lang3
+ 3.20.0
+ test
+
+
+ com.h2database
+ h2
+
+ 2.2.224
+ test
+
+
+ org.openjdk.jmh
+ jmh-core
+ ${commons.jmh.version}
+ test
+
+
+
+ scm:git:https://gitbox.apache.org/repos/asf/commons-csv.git
+ scm:git:https://gitbox.apache.org/repos/asf/commons-csv.git
+ https://gitbox.apache.org/repos/asf?p=commons-csv.git
+
+
+ https://issues.apache.org/jira/browse/CSV
+
+
+ github
+ https://github.com/apache/commons-csv/actions
+
+
+
+ apache.website
+ Apache Commons Site
+ scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-csv/
+
+
+
+ 1.15.0
+ (Java 8 or above)
+
+ RC1
+ 1.14.1
+ 1.15.1
+ csv
+ org.apache.commons.csv
+ CSV
+ 12313222
+ 1.8
+ 1.8
+
+ UTF-8
+ UTF-8
+ UTF-8
+ false
+ true
+ 2025-07-30T14:51:35Z
+ 1.22.0
+ 2.22.0
+
+
+ org.apache.commons.codec.binary;version="${commons.codec.version}",
+ org.apache.commons.io;version="${commons.io.version}",
+ org.apache.commons.io.build;version="${commons.io.version}",
+ org.apache.commons.io.function;version="${commons.io.version}",
+ org.apache.commons.io.input;version="${commons.io.version}",
+ org.apache.commons.io.output;version="${commons.io.version}",
+ *
+
+
+
+ true
+ 1.00
+ 0.99
+ 0.99
+ 0.97
+ 0.99
+ 0.97
+
+ ${basedir}/src/conf/checkstyle/checkstyle-header.txt
+ ${basedir}/src/conf/checkstyle/checkstyle.xml
+ ${basedir}/src/conf/checkstyle/checkstyle-suppressions.xml
+ LICENSE.txt, NOTICE.txt, **/maven-archiver/pom.properties
+
+
+ clean verify apache-rat:check japicmp:cmp spotbugs:check pmd:check pmd:cpd-check javadoc:javadoc checkstyle:check
+
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ ${commons.checkstyle-plugin.version}
+
+ ${checkstyle.config.file}
+ false
+ target/generated-test-sources/**/*.java
+ ${checkstyle.suppress.file}
+ true
+
+
+
+ org.apache.maven.plugins
+ maven-pmd-plugin
+ ${commons.pmd.version}
+
+ ${maven.compiler.target}
+ false
+
+
+
+
+
+ org.apache.rat
+ apache-rat-plugin
+
+
+
+
+ src/test/resources/org/apache/commons/csv/empty.txt
+ src/test/resources/org/apache/commons/csv/CSV-141/csv-141.csv
+ src/test/resources/org/apache/commons/csv/csv-167/sample1.csv
+ src/test/resources/org/apache/commons/csv/CSV-198/optd_por_public.csv
+ src/test/resources/org/apache/commons/csv/CSV-196/emoji.csv
+ src/test/resources/org/apache/commons/csv/CSV-196/japanese.csv
+ src/test/resources/org/apache/commons/csv/CSV-213/999751170.patch.csv
+ src/test/resources/org/apache/commons/csv/CSV-254/csv-254.csv
+ src/test/resources/org/apache/commons/csv/CSVFileParser/bom.csv
+ src/test/resources/org/apache/commons/csv/CSVFileParser/test.csv
+ src/test/resources/org/apache/commons/csv/CSVFileParser/test_default.txt
+ src/test/resources/org/apache/commons/csv/CSVFileParser/test_default_comment.txt
+ src/test/resources/org/apache/commons/csv/CSVFileParser/test_rfc4180.txt
+ src/test/resources/org/apache/commons/csv/CSVFileParser/test_rfc4180_trim.txt
+ src/test/resources/org/apache/commons/csv/CSVFileParser/testCSV85.csv
+ src/test/resources/org/apache/commons/csv/CSVFileParser/testCSV85_default.txt
+ src/test/resources/org/apache/commons/csv/CSVFileParser/testCSV85_ignoreEmpty.txt
+
+ src/test/resources/org/apache/commons/csv/ferc.gov/contract.txt
+ src/test/resources/org/apache/commons/csv/ferc.gov/transaction.txt
+ src/test/resources/**/*.bin
+ src/test/resources/org/apache/commons/csv/CSV-259/sample.txt
+ src/test/resources/org/apache/commons/csv/CSVFileParser/testCSV246.csv
+ src/test/resources/org/apache/commons/csv/CSVFileParser/testCSV246_checkWithNoComment.txt
+ src/test/resources/org/apache/commons/csv/CSV-290/psql.csv
+ src/test/resources/org/apache/commons/csv/CSV-290/psql.tsv
+
+
+
+
+
+
+
+ maven-compiler-plugin
+
+
+ **/*Benchmark*
+
+
+
+
+ maven-assembly-plugin
+
+
+ src/assembly/bin.xml
+ src/assembly/src.xml
+
+ gnu
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+
+ test-jar
+
+
+
+
+
+
+ ${commons.module.name}
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ **/perf/PerformanceTest.java
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+
+
+ com.github.spotbugs
+ spotbugs-maven-plugin
+
+ ${basedir}/src/site/resources/spotbugs/spotbugs-exclude-filter.xml
+
+
+
+
+ org.apache.maven.plugins
+ maven-pmd-plugin
+
+
+
+ org.apache.rat
+ apache-rat-plugin
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+
+
+
+
+ checkstyle
+
+
+
+
+
+ com.github.spotbugs
+ spotbugs-maven-plugin
+
+ ${basedir}/src/site/resources/spotbugs/spotbugs-exclude-filter.xml
+
+
+
+ org.apache.maven.plugins
+ maven-pmd-plugin
+
+
+ org.codehaus.mojo
+ taglist-maven-plugin
+
+
+
+
+ Needs Work
+
+
+ TODO
+ exact
+
+
+ FIXME
+ exact
+
+
+ XXX
+ exact
+
+
+
+
+ Notable Markers
+
+
+ NOTE
+ exact
+
+
+ NOPMD
+ exact
+
+
+ NOSONAR
+ exact
+
+
+
+
+
+
+
+
+ org.apache.rat
+ apache-rat-plugin
+
+
+
+
+
+
+
+ benchmark
+
+
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ ${commons.jmh.version}
+ test
+
+
+
+ genjava
+ gj-csv
+ 1.0
+ test
+
+
+
+ net.sourceforge.javacsv
+ javacsv
+ 2.0
+ test
+
+
+
+ com.opencsv
+ opencsv
+ 5.12.0
+ test
+
+
+
+ net.sf.supercsv
+ super-csv
+ 2.4.0
+ test
+
+
+
+ org.skife.kasparov
+ csv
+ 1.0
+ provided
+
+
+
+ org.apache.commons
+ commons-lang3
+ 3.20.0
+
+
+
+
+ true
+ org.apache
+
+
+
+
+
+
+ maven-compiler-plugin
+ ${commons.compiler.version}
+
+
+ **/*
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+
+
+ benchmark
+ test
+
+ exec
+
+
+ test
+ java
+
+ -classpath
+
+ org.openjdk.jmh.Main
+ -rf
+ json
+ -rff
+ target/jmh-result.json
+ ${benchmark}
+
+
+
+
+
+
+
+
+
+
+
+ bayard
+ Henri Yandell
+ bayard@apache.org
+ The Apache Software Foundation
+
+
+ Martin van den Bemt
+ mvdb
+ mvdb@apache.org
+ The Apache Software Foundation
+
+
+ Yonik Seeley
+ yonik
+ yonik@apache.org
+ The Apache Software Foundation
+
+
+ Emmanuel Bourg
+ ebourg
+ ebourg@apache.org
+ Apache
+
+
+ ggregory
+ Gary Gregory
+ ggregory at apache.org
+ https://www.garygregory.com
+ The Apache Software Foundation
+ https://www.apache.org/
+
+ PMC Member
+
+ America/New_York
+
+ https://people.apache.org/~ggregory/img/garydgregory80.png
+
+
+
+ Benedikt Ritter
+ britter
+ britter@apache.org
+ The Apache Software Foundation
+
+
+ Rob Tompkins
+ chtompki
+ chtompki@apache.org
+ The Apache Software Foundation
+
+
+
+
+ Bob Smith
+
+
+
diff --git a/src/assembly/bin.xml b/src/assembly/bin.xml
index 016f1fee9f..3526ca9e91 100644
--- a/src/assembly/bin.xml
+++ b/src/assembly/bin.xml
@@ -1,54 +1,56 @@
-
-
- bin
-
- tar.gz
- zip
-
-
-
-
- LICENSE.txt
- NOTICE.txt
- RELEASE-NOTES.txt
-
-
-
- target
-
-
- ${artifactId}-${version}.jar
-
-
-
- target/site/apidocs
- apidocs
-
- **/*
-
-
-
-
- target
-
-
- ${artifactId}-${version}-sources.jar
-
-
-
-
+
+
+ bin
+
+ tar.gz
+ zip
+
+
+
+
+ LICENSE.txt
+ NOTICE.txt
+ RELEASE-NOTES.txt
+
+
+
+ target
+
+
+ ${artifactId}-${version}.jar
+
+
+
+ target/site/apidocs
+ apidocs
+
+ **/*
+
+
+
+
+ target
+
+
+ ${artifactId}-${version}-sources.jar
+
+
+
+
diff --git a/src/assembly/src.xml b/src/assembly/src.xml
index 1c7392f955..1330db01f6 100644
--- a/src/assembly/src.xml
+++ b/src/assembly/src.xml
@@ -1,43 +1,45 @@
-
-
- src
-
- tar.gz
- zip
-
- ${artifactId}-${version}-src
-
-
-
- LICENSE*
- NOTICE*
- RELEASE-NOTES.txt
- pom.xml
- findbugs-exclude-filter.xml
- checkstyle*.xml
-
-
-
- src
-
- **/*Benchmark.java
-
-
-
-
-
+
+
+ src
+
+ tar.gz
+ zip
+
+ ${artifactId}-${version}-src
+
+
+
+ LICENSE*
+ NOTICE*
+ RELEASE-NOTES.txt
+ pom.xml
+ findbugs-exclude-filter.xml
+ checkstyle*.xml
+
+
+
+ src
+
+ **/*Benchmark.java
+
+
+
+
+
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index ce721ef83e..93952e9f18 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -1,177 +1,451 @@
-
-
-
-
-
-
-
- Release Notes
-
-
-
- Add predefined CSVFormats for printing MongoDB CSV anJ TSV.
- Fix escape character for POSTGRESQL_TEXT and POSTGRESQL_CSV formats.
- Site link "Source Repository" does not work.
- Add support for java.sql.Clob.
- Update to Java 8.
- Escape quotes in CLOBs #39.
- Update tests from H2 1.4.198 to 1.4.199.
-
-
- Add more documentation to CSVPrinter.
- Add autoFlush option for CsvPrinter. PR #24.
- The behavior of quote char using is not similar as Excel does when the first string contains CJK char(s).
- Don't quote cells just because they have UTF-8 encoded characters.
- Add API org.apache.commons.csv.CSVFormat.withSystemRecordSeparator().
- Inconsistency between Javadoc of CSVFormat DEFAULT EXCEL.
- Create CSVFormat.ORACLE preset.
- Some multi-iterator parsing peek sequences incorrectly consume elements.
- Parse method should avoid creating a redundant BufferedReader.
- Add predefined CSVFormats for printing MongoDB CSV and TSV.
-
-
- withNullString value is printed without quotes when QuoteMode.ALL is specified; add QuoteMode.ALL_NON_NULL. PR #17.
- Fix outdated comments about FileReader in CSVParser #13
- Fix incorrect method name 'withFirstRowAsHeader' in user guide.
- Negative numeric values in the first column are always quoted in minimal mode.
- Update platform requirement from Java 6 to 7.
- Do not use RuntimeException in CSVParser.iterator().new Iterator() {...}.getNextRecord()
- CSVParser: Add factory method accepting InputStream.
- Add convenience API CSVFormat.print(File, Charset)
- Add convenience API CSVFormat.print(Path, Charset)
- Add convenience API CSVParser.parse(Path, Charset, CSVFormat)
- Add convenience API CSVFormat#printer() to print to System.out
- Provide a CSV Format for printing PostgreSQL CSV and Text formats.
- Adding a placeholder in the Lexer and CSV parser to store the end-of-line string.
-
-
- Make CSVPrinter.print(Object) GC-free.
- Allow some printing operations directly from CSVFormat.
- Drop ferc.gov tests.
-
-
- Add shortcut method for using first record as header to CSVFormat
- Add withHeader(Class<? extends Enum>) to CSVFormat
- Comment line hides next record; update Javadoc to make behaviour clear
- CSVPrinter doesn't skip creation of header record if skipHeaderRecord is set to true
- Add IgnoreCase option for accessing header names
- The null string should be case-sensitive when reading records
- CSVFormat.nullString should not be escaped
- CSVFormat.MYSQL nullString should be "\N"
- Fix Javadoc to say CSVFormat with() methods return a new CSVFormat
- Support for ignoring trailing delimiter.
- Support trimming leading and trailing blanks.
- Create default formats for Informix UNLOAD and UNLOAD CSV.
-
-
- CSVFormat.with* methods clear the header comments
- Incorrect Javadoc on QuoteMode.NONE
- Add enum CSVFormat.Predefined that contains the default CSVFormat values.
-
-
- QuoteMode.NON_NUMERIC doesn't work with CSVPrinter.printRecords(ResultSet)
- CSVFormat#withHeader doesn't work well with #printComment, add withHeaderComments(String...)
- CSVFormat.EXCEL should ignore empty header names
- Incorrect Javadoc referencing org.apache.commons.csv.CSVFormat withQuote()
- Improve toString() implementation of CSVRecord
- Unified parameter validation
- Add CSVFormat#with 0-arg methods matching boolean arg methods
- Save positions of records to enable random access
- CSVPrinter.printRecord(ResultSet) with metadata
-
-
- No longer works with Java 6
- NullPointerException when empty header string and and null string of ""
- Validate format parameters in constructor
- IllegalArgumentException thrown when the header contains duplicate names when the column names are empty.
- CSVFormat#withHeader doesn't work with CSVPrinter
- CSVFormat is missing a print(...) method
- CSVRecord.toMap() throws NPE on formats with no
- headers.
- Check whether ISE/IAE are being used appropriately
- CSVFormat constructor should reject a header array with duplicate
- entries
-
- HeaderMap is inconsistent when it is parsed from an input with
- duplicate columns names
-
- CSVRecord.toMap() fails if row length shorter than header length
-
- CSVFormat.format allways append null
- Add Map conversion API to CSVRecord
- CSVParser: getHeaderMap throws NPE
- Lots of possible changes
- Use Character instead of char for char fields except delimiter
-
- Revert Builder implementation in CSVFormat
- CSVRecord does not verify that the length of the header mapping
- matches the number of values
-
- Allow the handling of NULL values
- Use the Builder pattern for CSVFormat
- Clarify comment handling
- CSVParser.nextValue() seems pointless
- Allow the String value for null to be customized for the CSV
- printer
-
- Not possible to create a CSVFormat from scratch
- Keep track of record number
- Lexer should only use char fields
- Need a way to extract parsed headers, e.g. for use in formatting
- output
-
- Header support
- Confusing semantic of the ignore leading/trailing spaces parameters
-
- Add convenience methods to CSVLexer
- Is CharBuffer really needed, now that StringBuilder is available?
-
- Replace while(true)-loop in CSVParser.getRecord with do-while-loop
-
- CSVFormat describes itself as immutable, but it is not - in
- particular it is not thread-safe
-
- Endless loops in CSV parser
- NullPointerException in CSVPrinter.print()/println()
- CSVPrinter overhaul
- Excel strategy uses wrong separator
- CSVStrategy has modifiable public static variables
-
- Predefined format for MYSQL
- Reduce visibility of methods in internal classes
- ExtendedBufferedReader does too much
- Decide whether to keep the csv.writer subpackage
-
-
-
-
+
+
+
+
+
+
+
+ Apache Commons CSV Release Notes
+
+
+
+
+ Remove Spotbugs dependency and use exclude-filter instead #564.
+ Remove broken website link #577.
+ Fix Apache RAT plugin console warnings.
+ [Javadoc] Clarify behavior of deprecated CSVFormat#withFirstRecordAsHeader() #2413.
+ CSVFormat.equals()/hashCode() ignores maxRows (#600).
+ ExtendedBufferedReader byte tracking leads to an incorrect CSVRecord.getBytePosition() (#601).
+ CSVFormat.Builder.setQuote() does not refresh quotedNullString (#2447).
+ Lexer.isDelimiter() accepts a partial multi-character delimiter at EOF (#603).
+ CSVParser applies characterOffset to bytePosition (#604).
+ CSVPrinter Reader printing with quote and escape can emit CSV that its parser cannot read back.
+ CSVParser applies maxRows to record numbers instead of rows produced when setRecordNumber(...) is used.
+ CSVParser with trackBytes enabled throws on multi-character delimiters containing supplementary Unicode characters.
+ CSVFormat.Builder.setNullString(String) can build an invalid quoted null string after setQuote(null).
+ Escape Reader values with quote and escape (#606).
+ Clear escape delimiter buffer before peek in Lexer.isEscapeDelimiter() (#608, #611).
+ Escape quote char in printWithEscapes when QuoteMode is NONE (#609).
+ Quote value starting with comment marker in minimal quote mode (#610).
+ Escape leading comment marker in printWithEscapes (#614).
+ Skip byte counting at EOF in ExtendedBufferedReader.read (#615).
+ Keep quoted empty trailing field with trailingDelimiter (#616).
+ Evaluate isDelimiter once in nextToken whitespace skip (#618)..
+
+ Add an "Android Compatibility" section to the web site.
+ Add CSVParser.Builder.setByteOffset(long) (#604).
+
+ Bump org.apache.commons:commons-parent from 85 to 102 #573, #595.
+ [test] Bump com.opencsv:opencsv from 5.11.2 to 5.12.0 #558.
+ Bump org.apache.commons:commons-lang3 from 3.18.0 to 3.20.0.
+ Bump commons-codec:commons-codec from 1.19.0 to 1.22.0.
+ Bump commons-io:commons-io from 2.20.0 to 2.22.0 #594.
+
+
+
+ CSVPrinter.printRecord(Stream) hangs if given a parallel stream.
+ CSVPrinter now uses an internal lock instead of synchronized methods.
+ org.apache.commons.csv.CSVPrinter.printRecords(ResultSet) now writes one record at a time using a lock.
+
+
+ Bump org.apache.commons:commons-parent from 81 to 85 #542.
+ Bump commons-io:commons-io from 2.18.0 to 2.20.0.
+ Bump com.opencsv:opencsv from 5.10 to 5.11.2 #545, #551, #553.
+ Bump org.apache.commons:commons-lang3 from 3.17.0 to 3.18.0 #556.
+ Bump commons-codec:commons-codec from 1.18.0 to 1.19.0.
+
+
+
+ Release history link changed from changes-report.html to changes.html #516.
+ Remove -nouses directive from maven-bundle-plugin. OSGi package imports now state 'uses' definitions for package imports, this doesn't affect JPMS (from org.apache.commons:commons-parent:80).
+ CSVParser.parse(URL, Charset, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)).
+ CSVParser.parse(String, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)).
+ CSVParser.parse(File, Charset, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)).
+ CSVParser.parse(Path, Charset, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)).
+ CSVParser.parse(InputStream, Charset, CSVFormat) with a null CSVFormat maps to CSVFormat.DEFAULT (like CSVParser.parse(Reader, CSVFormat)).
+ CSVParser.parse(*) methods with a null Charset maps to Charset.defaultCharset().
+ Fix possible NullPointerException in Token.toString().
+
+ Define and use Maven property commons.jmh.version.
+ Add CSVFormat.Builder.setMaxRows(long).
+ Add CSVFormat.getMaxRows().
+ CSVPrinter.printRecords(ResultSet) knows how to use CSVFormat's maxRows.
+ CSVPrinter.printRecords(Iterable) knows how to use CSVFormat's maxRows.
+ CSVPrinter.printRecords(Stream) knows how to use CSVFormat's maxRows.
+ CSVParser.stream() knows how to use CSVFormat's maxRows.
+ CSVParser.getRecords() knows how to use CSVFormat's maxRows.
+ CSVParser.iterator() knows how to use CSVFormat's maxRows.
+
+ Bump com.opencsv:opencsv from 5.9 to 5.10.
+ Bump commons-codec:commons-codec from 1.17.2 to 1.18.0 #522.
+ Bump org.apache.commons:commons-parent from 79 to 81.
+
+
+
+ Required OSGi Import-Package version numbers in MANIFEST.MF #504.
+ CSVParser.nextRecord() should throw CSVException (an IOException subclass) instead of IOException and IllegalStateException, no method signature changes needed.
+
+ Add CSVPrinter.getRecordCount().
+ Add and use CSVParser.Builder and builder() and deprecate CSVParser constructors.
+ CSVFormat.Builder implements Supplier<CSVFormat>.
+ Deprecate CSVFormat.Builder.build() for get().
+ Track byte position #502.
+
+ Bump org.apache.commons:commons-parent from 76 to 78 #486, #495.
+ Bump org.codehaus.mojo:taglist-maven-plugin from 3.1.0 to 3.2.1 #493.
+ Bump commons-io:commons-io from 2.17.0 to 2.18.0 #505.
+ Bump commons-codec:commons-codec from 1.17.1 to 1.17.2.
+ Bump org.apache.commons:commons-parent from 78 to 79.
+
+
+
+ Add CSVException that extends IOException thrown on invalid input instead of IOException.
+
+ Fix PMD issues for port to PMD 7.1.0.
+ Fix some Javadoc links #442.
+ Extract duplicated code into a method #444.
+ Migrate CSVFormat#print(File, Charset) to NIO #445.
+ Fix documentation for CSVFormat private constructor #466.
+ CSVFormat does not support explicit " as escape char.
+ Escaping is not disableable.
+ Fix Javadoc warnings on Java 23.
+ Improve parser performance by up to 20%, YMMV.
+
+ Bump commons-codec:commons-codec from 1.16.1 to 1.17.1 #422, #449.
+ Bump org.apache.commons:commons-parent from 69 to 76 #435, #452, #465, #468, #475, #482.
+ Bump org.codehaus.mojo:taglist-maven-plugin from 3.0.0 to 3.1.0 #441.
+ Bump org.apache.commons:commons-lang3 from 3.14.0 to 3.17.0 #450, #459, #470.
+ Bump org.hamcrest:hamcrest from 2.2 to 3.0 #455.
+ Bump commons-io:commons-io from 2.16.1 to 2.17.0 #476.
+
+
+
+ [Javadoc] Add example to CSVFormat#setHeaderComments() #344.
+ Add and use CSVFormat#setTrailingData(boolean) in CSVFormat.EXCEL for Excel compatibility #303.
+ Add and use CSVFormat#setLenientEof(boolean) in CSVFormat.EXCEL for Excel compatibility #303.
+
+ Replace deprecated method in user guide, update external link #324, #325.
+ Document duplicate header behavior #309.
+ Add missing docs #328.
+ [StepSecurity] CI: Harden GitHub Actions #329, #330.
+ Better error message during faulty CSV record read #347.
+ Misleading error message when QuoteMode set to None #352.
+ OutOfMemory for very long rows despite using column value of type Reader.
+ Use try-with-resources to manage JDBC CLOB in CSVPrinter.printRecords(ResultSet).
+ JDBC Blob columns are now output as Base64 instead of Object#toString(), which usually is InputStream#toString().
+ Support unusual Excel use cases: Add support for trailing data after the closing quote, and EOF without a final closing quote #303.
+ MongoDB CSV empty first column parsing fix #412.
+
+ Bump commons-io:commons-io: from 2.11.0 to 2.16.1 #408, #413.
+ Bump commons-parent from 57 to 69 #410.
+ Bump h2 from 2.1.214 to 2.2.224 #333, #349, #359.
+ Bump commons-lang3 from 3.12.0 to 3.14.0.
+ Update exception message in CSVRecord#getNextRecord() #348.
+ Bump tests using com.opencsv:opencsv from 5.8 to 5.9 #373.
+
+
+
+ Minor changes #172.
+ No Automatic-Module-Name prevents usage in JPMS projects without repacking the JAR.
+ Fix for multi-char delimiter not working as expected #218.
+ CSVRecord.get(Enum) should use Enum.name() instead of Enum.toString().
+ Allow org.apache.commons.csv.IOUtils.copy(Reader, Appendable, CharBuffer) to compile on Java 11 and run on Java 8.
+ CSVRecord.toList() does not give write access to the new List.
+ CSVParser.getRecords() now throws UncheckedIOException instead of IOException.
+ Add comments to iterator() and stream() #270.
+ Fix wrong assumptions in PostgreSQL formats #265.
+ Validate input to setDelimiter(String) for empty string #266.
+ Bump CSVFormat#serialVersionUID from 1 to 2.
+ CSVParser: Identify duplicates in null, empty and blank header names #279.
+
+ Serialization in CSVFormat is not supported from one version to the next.
+
+ Make CSVRecord#values() public.
+ Add DuplicateHeaderMode for flexibility with header strictness. #114.
+ Support for parallelism in CSVPrinter.
+ Add CSVPrinter.printRecord[s](Stream).
+ Add accessors for header/trailer comments #257.
+ Add github/codeql-action.
+
+ Bump actions/cache from 2.1.6 to 3.0.10 #196, #233, #243, #267, #271.
+ Bump actions/checkout from 2.3.4 to 3.1.0 #188, #195, #220, #272.
+ Bump actions/setup-java from 2 to 3.5.1.
+ Bump actions/upload-artifact from 3.1.0 to 3.1.1 #280.
+ Bump commons-parent from 52 to 57 #264, #288, #298, #323.
+ Bump checkstyle from 8.44 to 9.2.1 #180, #190, #194, #202, #207.
+ Bump junit-jupiter from 5.8.0-M1 to 5.9.1 #179, #186, #201, #244, #263.
+ Bump jmh-core from 1.32 to 1.36 #176, #208, #229, #285.
+ Bump jmh-generator-annprocess from 1.32 to 1.36 #175, #206, #226, #283.
+ Bump mockito-core from 3.11.2 to 4.11.0 #187, #197, #204, #212, #230, #237, #251, #259, #284, #292, #297.
+ Bump maven-pmd-plugin from 3.14.0 to 3.19.0 #184, #219, #238, #254, #258.
+ Bump pmd from 6.36.0 to 6.52.0 #173, #189, #193, #199, #227, #233, #214, #236, #240, #247, #255, #273.
+ Bump opencsv from 5.5.1 to 5.7.1 #182, #221, #260, #281.
+ Bump spotbugs-maven-plugin from 4.3.0 to 4.7.3.0 #192, #198, #203, #211, #225, #234, #242, #245, #261, #275, #282.
+ Bump com.github.spotbugs:spotbugs from 4.5.3 to 4.7.2.
+ Bump h2 from 1.4.200 to 2.1.214 #200, #205, #213, #239.
+ Bump maven-javadoc-plugin from 3.3.0 to 3.4.1.
+ Bump biz.aQute.bnd:biz.aQute.bndlib from 5.3.0 to 6.3.1.
+ Bump jacoco-maven-plugin from 0.8.7 to 0.8.8.
+ Bump japicmp-maven-plugin from 0.15.3 to 0.16.0.
+ Bump maven-checkstyle-plugin from 3.1.2 to 3.2.0 #253.
+
+
+
+ Replace FindBugs with SpotBugs #56.
+ Javadoc typo in CSVFormat let's -> lets #57.
+ CSVFormat.printWithEscapes throws StringIndexOutOfBoundsException when value is Reader #61.
+ Improve CSVFormat test coverage #63.
+ Fix CSVFileParserTest.java to allow for a null return value from record.getComment() #62.
+ Improve test coverage in CSVFormatTest #65.
+ Removed invalid Javadoc markup for CSVFormat EXCEL #64.
+ Improve CSVRecord and CSVPrinter code coverage #66.
+ Improve lexer and token coverage #67.
+ CSVFormat.format trims last delimiter if the delimiter is a white space #71.
+ Replace org.apache.commons.csv.Assertions.notNull() with Objects.requireNonNull().
+ Line number is not proper at EOF.
+ Parser iterates over the last CSV Record twice.
+ Minor improvements #126, #127, #130.
+ Add possibility to use ResultSet header meta data as CSV header #11.
+ Add test cases for withIgnoreSurroundingSpaces() and withTrim() #70.
+ Update CSVParser.parse(File, Charset, CSVFormat) from IO to NIO.
+ Missing separator with print(object) followed by printRecord(Object[]) #157.
+ Fix EOL checking for read array in ExtendedBufferedReader #5.
+ Print from Reader with embedded quotes generates incorrect output #78.
+ Replace JUnit assert by simpler but equivalent calls. #159.
+ Update gitignore to ignore idea and vscode #160.
+ Update CSVBenchmark #165.
+ Remove Whitespace Check Determines Delimiter Twice #167.
+ Document and Automate CSV Benchmark Harness #166.
+ Optimize Lexer Delimiter Check for One Character Delimiter #163.
+ SpotBugs Error: Medium: org.apache.commons.csv.CSVParser.getHeaderNames() may expose internal representation by returning CSVParser.headerNames [org.apache.commons.csv.CSVParser] At CSVParser.java:[line 599] EI_EXPOSE_REP.
+ SpotBugs Error: Medium: new org.apache.commons.csv.CSVParser(Reader, CSVFormat, long, long) may expose internal representation by storing an externally mutable object into CSVParser.format [org.apache.commons.csv.CSVParser] At CSVParser.java:[line 433] EI_EXPOSE_REP2.
+ SpotBugs Error: Medium: new org.apache.commons.csv.CSVParser(Reader, CSVFormat, long, long) may expose internal representation by storing an externally mutable object into CSVParser.headerMap [org.apache.commons.csv.CSVParser] At CSVParser.java:[line 437] EI_EXPOSE_REP2.
+ SpotBugs Error: Medium: new org.apache.commons.csv.CSVParser(Reader, CSVFormat, long, long) may expose internal representation by storing an externally mutable object into CSVParser.headerNames [org.apache.commons.csv.CSVParser] At CSVParser.java:[line 438] EI_EXPOSE_REP2.
+ SpotBugs Error: Medium: new org.apache.commons.csv.CSVPrinter(Appendable, CSVFormat) may expose internal representation by storing an externally mutable object into CSVPrinter.format [org.apache.commons.csv.CSVPrinter] At CSVPrinter.java:[line 100] EI_EXPOSE_REP2.
+ Formalize PerformanceTest #168.
+ Reuse Buffers in Lexer for Delimiter Detection #162.
+ Cleanup and Document Performance Test Harness #170.
+ Update buffer position when reading line comment #120.
+
+ Make CSVRecord#toList() public.
+ Add CSVRecord#stream().
+ Add CSVParser#stream().
+ Make the method CSVRecord.putIn(Map) public.
+ Add test cases for CSVRecord with get(Enum) and toString. #54.
+ Add and use CSVFormat.Builder, deprecated CSVFormat#with methods, based on #73.
+ Add support for String delimiters #76.
+
+ Update org.junit.jupiter:junit-jupiter from 5.6.0 to 5.7.0, #84 #109
+ Update tests from Apache Commons Lang 3.9 to 3.12.0.
+ Update tests from commons-io:commons-io 2.6 to 2.11.0, #108.
+ Bump actions/checkout from v1 to v2.3.4, #79, #92, #121.
+ Bump commons-parent from 50 to 51 #80.
+ Bump tests from opencsv from 3.1 to 5.5.1 #81, #137, #158.
+ Update tests from super-csv from 2.2.1 to 2.4.0 #86.
+ Bump build actions/setup-java from v1.4.0 to v2, #101, #113.
+ Bump maven-pmd-plugin from 3.13.0 to 3.14.0 #122.
+ Bump tests from org.mockito:mockito-core 3.2.4 -> 3.11.2; #88, #107, #110, #123, #128, #129, #156.
+ Bump actions/cache from v2 to v2.1.6 #132, #153.
+ Bump maven-checkstyle-plugin from 3.0.0 to 3.1.2 #131.
+ Bump checkstyle from 8.29 to 8.44.
+ Bump junit-jupiter from 5.7.0 to 5.8.0-M1 #133, #149.
+ Bump commons.jacoco.version from 0.8.5 to 0.8.7 (Java 16).
+ Bump commons.spotbugs.version from 4.0.4 to 4.3.0 (Java 16).
+ Bump maven-javadoc-plugin from 3.2.0 to 3.3.0.
+ Bump jmh-generator-annprocess from 1.5.2 to 1.32 #151.
+ Bump PMD core from 6.29.0 to 6.36.0.
+ Bump biz.aQute.bnd:biz.aQute.bndlib from 5.1.2 to 5.3.0.
+
+
+ Add CSVRecord.isSet(int) method #52.
+ Char escape doesn't work properly with quoting.
+ Test case failures following CSVFormat#equals() update.
+ CSVFormat withTrim() and withIgnoreSurroundingSpaces() need better docs.
+ CSVFormat equals() and hashCode() don't use all fields.
+ CSVFormat#validate() does not account for allowDuplicateHeaderNames #43.
+ Post 1.7 release fixes.
+ Upgrade test framework to JUnit 5 Jupiter #49, #50.
+ A single empty header is allowed when not allowing empty column headers. #47.
+ CSVRecord is not Serializable.
+ Use test scope for supercsv #48.
+ Update tests from H2 1.4.199 to 1.4.200.
+ Update tests from Hamcrest 2.1 to 2.2.
+ Update tests from Mockito 3.1.0 to 3.2.4.
+ Fix typos in site and test #53.
+ Fix typo performance test #55.
+
+
+ Add predefined CSVFormats for printing MongoDB CSV and TSV.
+ Fix escape character for POSTGRESQL_TEXT and POSTGRESQL_CSV formats.
+ Site link "Source Repository" does not work.
+ Add support for java.sql.Clob.
+ Update to Java 8.
+ Escape quotes in CLOBs #39.
+ Cannot get headers in column order from CSVRecord.
+ Update tests from H2 1.4.198 to 1.4.199.
+
+
+ Add more documentation to CSVPrinter.
+ Add autoFlush option for CsvPrinter. PR #24.
+ The behavior of quote char using is not similar as Excel does when the first string contains CJK char(s).
+ Don't quote cells just because they have UTF-8 encoded characters.
+ Add API org.apache.commons.csv.CSVFormat.withSystemRecordSeparator().
+ Inconsistency between Javadoc of CSVFormat DEFAULT EXCEL.
+ Create CSVFormat.ORACLE preset.
+ Some multi-iterator parsing peek sequences incorrectly consume elements.
+ Parse method should avoid creating a redundant BufferedReader.
+ Add predefined CSVFormats for printing MongoDB CSV and TSV.
+
+
+ withNullString value is printed without quotes when QuoteMode.ALL is specified; add QuoteMode.ALL_NON_NULL. PR #17.
+ Fix outdated comments about FileReader in CSVParser #13
+ Fix incorrect method name 'withFirstRowAsHeader' in user guide.
+ Negative numeric values in the first column are always quoted in minimal mode.
+ Update platform requirement from Java 6 to 7.
+ Do not use RuntimeException in CSVParser.iterator().new Iterator() {...}.getNextRecord()
+ CSVParser: Add factory method accepting InputStream.
+ Add convenience API CSVFormat.print(File, Charset)
+ Add convenience API CSVFormat.print(Path, Charset)
+ Add convenience API CSVParser.parse(Path, Charset, CSVFormat)
+ Add convenience API CSVFormat#printer() to print to System.out
+ Provide a CSV Format for printing PostgreSQL CSV and Text formats.
+ Adding a placeholder in the Lexer and CSV parser to store the end-of-line string.
+
+
+ Make CSVPrinter.print(Object) GC-free.
+ Allow some printing operations directly from CSVFormat.
+ Drop ferc.gov tests.
+
+
+ Add shortcut method for using first record as header to CSVFormat
+ Add withHeader(Class<? extends Enum>) to CSVFormat
+ Comment line hides next record; update Javadoc to make behavior clear
+ CSVPrinter doesn't skip creation of header record if skipHeaderRecord is set to true
+ Add IgnoreCase option for accessing header names
+ The null string should be case-sensitive when reading records
+ CSVFormat.nullString should not be escaped
+ CSVFormat.MYSQL nullString should be "\N"
+ Fix Javadoc to say CSVFormat with() methods return a new CSVFormat
+ Support for ignoring trailing delimiter.
+ Support trimming leading and trailing blanks.
+ Create default formats for Informix UNLOAD and UNLOAD CSV.
+
+
+ CSVFormat.with* methods clear the header comments
+ Incorrect Javadoc on QuoteMode.NONE
+ Add enum CSVFormat.Predefined that contains the default CSVFormat values.
+
+
+ QuoteMode.NON_NUMERIC doesn't work with CSVPrinter.printRecords(ResultSet)
+ CSVFormat#withHeader doesn't work well with #printComment, add withHeaderComments(String...)
+ CSVFormat.EXCEL should ignore empty header names
+ Incorrect Javadoc referencing org.apache.commons.csv.CSVFormat withQuote()
+ Improve toString() implementation of CSVRecord
+ Unified parameter validation
+ Add CSVFormat#with 0-arg methods matching boolean arg methods
+ Save positions of records to enable random access
+ CSVPrinter.printRecord(ResultSet) with metadata
+
+
+ No longer works with Java 6
+ NullPointerException when empty header string and null string of ""
+ Validate format parameters in constructor
+ IllegalArgumentException thrown when the header contains duplicate names when the column names are empty.
+ CSVFormat#withHeader doesn't work with CSVPrinter
+ CSVFormat is missing a print(...) method
+ CSVRecord.toMap() throws NPE on formats with no
+ headers.
+ Check whether ISE/IAE are being used appropriately
+ CSVFormat constructor should reject a header array with duplicate
+ entries
+
+ HeaderMap is inconsistent when it is parsed from an input with
+ duplicate columns names
+
+ CSVRecord.toMap() fails if row length shorter than header length
+
+ CSVFormat.format allways append null
+ Add Map conversion API to CSVRecord
+ CSVParser: getHeaderMap throws NPE
+ Lots of possible changes
+ Use Character instead of char for char fields except delimiter
+
+ Revert Builder implementation in CSVFormat
+ CSVRecord does not verify that the length of the header mapping
+ matches the number of values
+
+ Allow the handling of NULL values
+ Use the Builder pattern for CSVFormat
+ Clarify comment handling
+ CSVParser.nextValue() seems pointless
+ Allow the String value for null to be customized for the CSV
+ printer
+
+ Not possible to create a CSVFormat from scratch
+ Keep track of record number
+ Lexer should only use char fields
+ Need a way to extract parsed headers, e.g. for use in formatting
+ output
+
+ Header support
+ Confusing semantic of the ignore leading/trailing spaces parameters
+
+ Add convenience methods to CSVLexer
+ Is CharBuffer really needed, now that StringBuilder is available?
+
+ Replace while(true)-loop in CSVParser.getRecord with do-while-loop
+
+ CSVFormat describes itself as immutable, but it is not - in
+ particular it is not thread-safe
+
+ Endless loops in CSV parser
+ NullPointerException in CSVPrinter.print()/println()
+ CSVPrinter overhaul
+ Excel strategy uses wrong separator
+ CSVStrategy has modifiable public static variables
+
+ Predefined format for MYSQL
+ Reduce visibility of methods in internal classes
+ ExtendedBufferedReader does too much
+ Decide whether to keep the csv.writer subpackage
+
+
+
+
diff --git a/src/changes/release-notes.vm b/src/changes/release-notes.vm
index 5275b6ffb9..5769829552 100644
--- a/src/changes/release-notes.vm
+++ b/src/changes/release-notes.vm
@@ -6,7 +6,7 @@
## "License"); you may not use this file except in compliance
## with the License. You may obtain a copy of the License at
##
-## http://www.apache.org/licenses/LICENSE-2.0
+## https://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing,
## software distributed under the License is distributed on an
@@ -15,22 +15,21 @@
## specific language governing permissions and limitations
## under the License.
##
- ${project.name}
- Version ${version}
- Release Notes
+${project.name} ${version} Release Notes
+------------------------------------------------
+The ${developmentTeam} is pleased to announce the release of ${project.name} ${version}.
-INTRODUCTION:
-This document contains the release notes for the ${version} version of Apache Commons CSV.
-Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
+This document contains the release notes for the ${version} version of ${project.name}.
+Commons CSV reads and writes files in Comma Separated Value (CSV) format variations.
-CSV requires at least Java 6.
+Commons CSV requires at least Java 8.
$introduction.replaceAll("(?
+
+
+
+
+
+
+
diff --git a/src/conf/checkstyle/checkstyle.xml b/src/conf/checkstyle/checkstyle.xml
new file mode 100644
index 0000000000..4e8691243c
--- /dev/null
+++ b/src/conf/checkstyle/checkstyle.xml
@@ -0,0 +1,91 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/apache/commons/csv/Assertions.java b/src/main/java/org/apache/commons/csv/Assertions.java
deleted file mode 100644
index 057b3d7442..0000000000
--- a/src/main/java/org/apache/commons/csv/Assertions.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.commons.csv;
-
-import java.util.Objects;
-
-/**
- * Utility class for input parameter validation.
- *
- * TODO Replace usage with {@link Objects} when we switch to Java 7.
- */
-final class Assertions {
-
- private Assertions() {
- // can not be instantiated
- }
-
- static void notNull(final Object parameter, final String parameterName) {
- if (parameter == null) {
- throw new IllegalArgumentException("Parameter '" + parameterName + "' must not be null!");
- }
- }
-}
diff --git a/src/main/java/org/apache/commons/csv/CSVException.java b/src/main/java/org/apache/commons/csv/CSVException.java
new file mode 100644
index 0000000000..a986148f34
--- /dev/null
+++ b/src/main/java/org/apache/commons/csv/CSVException.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.commons.csv;
+
+import java.io.IOException;
+import java.util.Formatter;
+import java.util.IllegalFormatException;
+
+/**
+ * Signals a CSV exception. For example, this exception is thrown when parsing invalid input.
+ *
+ * @since 1.12.0
+ */
+public class CSVException extends IOException {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Constructs a new instance with a formatted message.
+ *
+ * @param format A {@link Formatter} format string.
+ * @param args See {@link String#format(String, Object...)}.
+ * @throws IllegalFormatException See {@link String#format(String, Object...)}.
+ */
+ public CSVException(final String format, final Object... args) {
+ super(String.format(format, args));
+ }
+
+}
diff --git a/src/main/java/org/apache/commons/csv/CSVFormat.java b/src/main/java/org/apache/commons/csv/CSVFormat.java
index 6f77bef535..7145d23d3b 100644
--- a/src/main/java/org/apache/commons/csv/CSVFormat.java
+++ b/src/main/java/org/apache/commons/csv/CSVFormat.java
@@ -1,38 +1,30 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
-import static org.apache.commons.csv.Constants.BACKSLASH;
-import static org.apache.commons.csv.Constants.COMMA;
-import static org.apache.commons.csv.Constants.COMMENT;
-import static org.apache.commons.csv.Constants.CR;
-import static org.apache.commons.csv.Constants.CRLF;
-import static org.apache.commons.csv.Constants.DOUBLE_QUOTE_CHAR;
-import static org.apache.commons.csv.Constants.EMPTY;
-import static org.apache.commons.csv.Constants.LF;
-import static org.apache.commons.csv.Constants.PIPE;
-import static org.apache.commons.csv.Constants.SP;
-import static org.apache.commons.csv.Constants.TAB;
+import static org.apache.commons.io.IOUtils.EOF;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.OutputStreamWriter;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringWriter;
@@ -45,10 +37,18 @@
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
+import java.util.Objects;
import java.util.Set;
+import java.util.function.Supplier;
+
+import org.apache.commons.codec.binary.Base64OutputStream;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.function.IOStream;
+import org.apache.commons.io.function.Uncheck;
+import org.apache.commons.io.output.AppendableOutputStream;
/**
- * Specifies the format of a CSV file and parses input.
+ * Specifies the format of a CSV file for parsing and writing.
*
*
Using predefined formats
*
@@ -61,11 +61,13 @@
*
{@link #EXCEL}
*
{@link #INFORMIX_UNLOAD}
*
{@link #INFORMIX_UNLOAD_CSV}
+ *
{@link #MONGODB_CSV}
+ *
{@link #MONGODB_TSV}
*
{@link #MYSQL}
- *
{@link #RFC4180}
*
{@link #ORACLE}
*
{@link #POSTGRESQL_CSV}
*
{@link #POSTGRESQL_TEXT}
+ *
{@link #RFC4180}
*
{@link #TDF}
*
*
@@ -88,12 +90,12 @@
*
Defining formats
*
*
- * You can extend a format by calling the {@code with} methods. For example:
+ * You can extend a format by calling the {@code set} methods. For example:
*
- * Calling {@link #withHeader(String...)} let's you use the given names to address values in a {@link CSVRecord}, and
- * assumes that your CSV source does not contain a first record that also defines column names.
+ * Calling {@link Builder#setHeader(String...)} lets you use the given names to address values in a {@link CSVRecord}, and assumes that your CSV source does not
+ * contain a first record that also defines column names.
*
* If it does, then you are overriding this metadata with your names and you should skip the first record by calling
- * {@link #withSkipHeaderRecord(boolean)} with {@code true}.
+ * {@link Builder#setSkipHeaderRecord(boolean)} with {@code true}.
*
*
*
Parsing
@@ -119,10 +121,10 @@
* You can use a format directly to parse a reader. For example, to parse an Excel file with columns header, write:
*
*
- *
* For other input types, like resources, files, and URLs, use the static methods on {@link CSVParser}.
@@ -131,12 +133,12 @@
*
Referencing columns safely
*
*
- * If your source contains a header record, you can simplify your code and safely reference columns, by using
- * {@link #withHeader(String...)} with no arguments:
+ * If your source contains a header record, you can simplify your code and safely reference columns, by using {@link Builder#setHeader(String...)} with no
+ * arguments:
*
All other values take their Java defaults, {@code false} for booleans, {@code null} for object references.
+ *
+ *
+ * @see Predefined#Default
+ * @see DuplicateHeaderMode#ALLOW_ALL
+ *
+ * @return a copy of the builder
+ */
+ public static Builder create() {
+ // @formatter:off
+ return new Builder()
+ .setDelimiter(Constants.COMMA)
+ .setQuote(Constants.DOUBLE_QUOTE_CHAR)
+ .setRecordSeparator(Constants.CRLF)
+ .setIgnoreEmptyLines(true)
+ .setDuplicateHeaderMode(DuplicateHeaderMode.ALLOW_ALL);
+ // @formatter:on
+ }
+
+ /**
+ * Creates a new builder from the given format.
+ *
+ * @param csvFormat the source format.
+ * @return a new builder.
+ */
+ public static Builder create(final CSVFormat csvFormat) {
+ return new Builder(csvFormat);
+ }
+
+ private boolean allowMissingColumnNames;
+
+ private boolean autoFlush;
+
+ private Character commentMarker;
+
+ private String delimiter;
+
+ private DuplicateHeaderMode duplicateHeaderMode;
+
+ private Character escapeCharacter;
+
+ private String[] headerComments;
+
+ private String[] headers;
+
+ private boolean ignoreEmptyLines;
+
+ private boolean ignoreHeaderCase;
+
+ private boolean ignoreSurroundingSpaces;
+
+ private String nullString;
+
+ private Character quoteCharacter;
+
+ private String quotedNullString;
+
+ private QuoteMode quoteMode;
+
+ private String recordSeparator;
+
+ private boolean skipHeaderRecord;
+
+ private boolean lenientEof;
+
+ private boolean trailingData;
+
+ private boolean trailingDelimiter;
+
+ private boolean trim;
+
+ /** The maximum number of rows to process, excluding the header row. */
+ private long maxRows;
+
+ private Builder() {
+ // empty
+ }
+
+ private Builder(final CSVFormat csvFormat) {
+ this.allowMissingColumnNames = csvFormat.allowMissingColumnNames;
+ this.autoFlush = csvFormat.autoFlush;
+ this.commentMarker = csvFormat.commentMarker;
+ this.delimiter = csvFormat.delimiter;
+ this.duplicateHeaderMode = csvFormat.duplicateHeaderMode;
+ this.escapeCharacter = csvFormat.escapeCharacter;
+ this.headerComments = csvFormat.headerComments;
+ this.headers = csvFormat.headers;
+ this.ignoreEmptyLines = csvFormat.ignoreEmptyLines;
+ this.ignoreHeaderCase = csvFormat.ignoreHeaderCase;
+ this.ignoreSurroundingSpaces = csvFormat.ignoreSurroundingSpaces;
+ this.lenientEof = csvFormat.lenientEof;
+ this.maxRows = csvFormat.maxRows;
+ this.nullString = csvFormat.nullString;
+ this.quoteCharacter = csvFormat.quoteCharacter;
+ this.quoteMode = csvFormat.quoteMode;
+ this.quotedNullString = csvFormat.quotedNullString;
+ this.recordSeparator = csvFormat.recordSeparator;
+ this.skipHeaderRecord = csvFormat.skipHeaderRecord;
+ this.trailingData = csvFormat.trailingData;
+ this.trailingDelimiter = csvFormat.trailingDelimiter;
+ this.trim = csvFormat.trim;
+ }
+
+ /**
+ * Builds a new CSVFormat instance.
+ *
+ * @return a new CSVFormat instance.
+ * @deprecated Use {@link #get()}.
+ */
+ @Deprecated
+ public CSVFormat build() {
+ return get();
+ }
+
+ /**
+ * Builds a new CSVFormat instance.
+ *
+ * @return a new CSVFormat instance.
+ * @since 1.13.0
+ */
+ @Override
+ public CSVFormat get() {
+ return new CSVFormat(this);
+ }
+
+ /**
+ * Sets the duplicate header names behavior, true to allow, false to disallow.
+ *
+ * @param allowDuplicateHeaderNames the duplicate header names behavior, true to allow, false to disallow.
+ * @return This instance.
+ * @deprecated Use {@link #setDuplicateHeaderMode(DuplicateHeaderMode)}.
+ */
+ @Deprecated
+ public Builder setAllowDuplicateHeaderNames(final boolean allowDuplicateHeaderNames) {
+ setDuplicateHeaderMode(allowDuplicateHeaderNames ? DuplicateHeaderMode.ALLOW_ALL : DuplicateHeaderMode.ALLOW_EMPTY);
+ return this;
+ }
+
+ /**
+ * Sets the parser missing column names behavior, {@code true} to allow missing column names in the header line, {@code false} to cause an
+ * {@link IllegalArgumentException} to be thrown.
+ *
+ * @param allowMissingColumnNames the missing column names behavior, {@code true} to allow missing column names in the header line, {@code false} to
+ * cause an {@link IllegalArgumentException} to be thrown.
+ * @return This instance.
+ */
+ public Builder setAllowMissingColumnNames(final boolean allowMissingColumnNames) {
+ this.allowMissingColumnNames = allowMissingColumnNames;
+ return this;
+ }
+
+ /**
+ * Sets whether to flush on close.
+ *
+ * @param autoFlush whether to flush on close.
+ * @return This instance.
+ */
+ public Builder setAutoFlush(final boolean autoFlush) {
+ this.autoFlush = autoFlush;
+ return this;
+ }
+
+ /**
+ * Sets the comment marker character, use {@code null} to disable comments.
+ *
+ * The comment start character is only recognized at the start of a line.
+ *
+ *
+ * Comments are printed first, before headers.
+ *
+ *
+ * Use {@link #setCommentMarker(char)} or {@link #setCommentMarker(Character)} to set the comment marker written at the start of each comment line.
+ *
+ *
+ * If the comment marker is not set, then the header comments are ignored.
+ *
+ *
+ * For example:
+ *
+ *
+ *
+ * builder.setCommentMarker('#').setHeaderComments("Generated by Apache Commons CSV", Instant.ofEpochMilli(0));
+ *
+ *
+ * @param commentMarker the comment start marker, use {@code null} to disable.
+ * @return This instance.
+ * @throws IllegalArgumentException thrown if the specified character is a line break
+ */
+ public Builder setCommentMarker(final char commentMarker) {
+ setCommentMarker(Character.valueOf(commentMarker));
+ return this;
+ }
+
+ /**
+ * Sets the comment marker character, use {@code null} to disable comments.
+ *
+ * The comment start character is only recognized at the start of a line.
+ *
+ *
+ * Comments are printed first, before headers.
+ *
+ *
+ * Use {@link #setCommentMarker(char)} or {@link #setCommentMarker(Character)} to set the comment marker written at the start of each comment line.
+ *
+ *
+ * If the comment marker is not set, then the header comments are ignored.
+ *
+ *
+ * For example:
+ *
+ *
+ *
+ * builder.setCommentMarker('#').setHeaderComments("Generated by Apache Commons CSV", Instant.ofEpochMilli(0));
+ *
+ * The header is also used by the {@link CSVPrinter}.
+ *
+ *
+ * @param headerEnum the enum defining the header, {@code null} if disabled, empty if parsed automatically, user-specified otherwise.
+ * @return This instance.
+ */
+ public Builder setHeader(final Class extends Enum>> headerEnum) {
+ String[] header = null;
+ if (headerEnum != null) {
+ final Enum>[] enumValues = headerEnum.getEnumConstants();
+ header = new String[enumValues.length];
+ Arrays.setAll(header, i -> enumValues[i].name());
+ }
+ return setHeader(header);
+ }
+
+ /**
+ * Sets the header from the result set metadata. The header can be parsed automatically from the input file with:
+ *
+ *
+ * builder.setHeader();
+ *
+ *
+ * or specified manually with:
+ *
+ *
+ * builder.setHeader(resultSet);
+ *
+ *
+ * The header is also used by the {@link CSVPrinter}.
+ *
+ *
+ * @param resultSet the resultSet for the header, {@code null} if disabled, empty if parsed automatically, user-specified otherwise.
+ * @return This instance.
+ * @throws SQLException SQLException if a database access error occurs or this method is called on a closed result set.
+ */
+ public Builder setHeader(final ResultSet resultSet) throws SQLException {
+ return setHeader(resultSet != null ? resultSet.getMetaData() : null);
+ }
+
+ /**
+ * Sets the header from the result set metadata. The header can be parsed automatically from the input file with:
+ *
+ *
+ * builder.setHeader();
+ *
+ *
+ * or specified manually with:
+ *
+ *
+ * builder.setHeader(resultSetMetaData);
+ *
+ *
+ * The header is also used by the {@link CSVPrinter}.
+ *
+ *
+ * @param resultSetMetaData the metaData for the header, {@code null} if disabled, empty if parsed automatically, user-specified otherwise.
+ * @return This instance.
+ * @throws SQLException SQLException if a database access error occurs or this method is called on a closed result set.
+ */
+ public Builder setHeader(final ResultSetMetaData resultSetMetaData) throws SQLException {
+ String[] labels = null;
+ if (resultSetMetaData != null) {
+ final int columnCount = resultSetMetaData.getColumnCount();
+ labels = new String[columnCount];
+ for (int i = 0; i < columnCount; i++) {
+ labels[i] = resultSetMetaData.getColumnLabel(i + 1);
+ }
+ }
+ return setHeader(labels);
+ }
+
+ /**
+ * Sets the header to the given values. The header can be parsed automatically from the input file with:
+ *
+ *
+ * The header is also used by the {@link CSVPrinter}.
+ *
+ *
+ * This method keeps a copy of the input array.
+ *
+ *
+ * @param header the header, {@code null} if disabled, empty if parsed automatically, user-specified otherwise.
+ * @return This instance.
+ */
+ public Builder setHeader(final String... header) {
+ this.headers = CSVFormat.clone(header);
+ return this;
+ }
+
+ /**
+ * Sets the header comments to write before the CSV data.
+ *
+ * This setting is ignored by the parser.
+ *
+ *
+ * Comments are printed first, before headers.
+ *
+ *
+ * Use {@link #setCommentMarker(char)} or {@link #setCommentMarker(Character)} to set the comment marker written at the start of each comment line.
+ *
+ *
+ * If the comment marker is not set, then the header comments are ignored.
+ *
+ *
+ * For example:
+ *
+ *
+ *
+ * builder.setCommentMarker('#').setHeaderComments("Generated by Apache Commons CSV", Instant.ofEpochMilli(0));
+ *
+ * This method keeps a copy of the input array.
+ *
+ *
+ * @param headerComments the headerComments which will be printed by the Printer before the CSV data.
+ * @return This instance.
+ */
+ public Builder setHeaderComments(final Object... headerComments) {
+ this.headerComments = CSVFormat.clone(toStringArray(headerComments));
+ return this;
+ }
+
+ /**
+ * Sets the header comments to write before the CSV data.
+ *
+ * This setting is ignored by the parser.
+ *
+ *
+ * Comments are printed first, before headers.
+ *
+ *
+ * Use {@link #setCommentMarker(char)} or {@link #setCommentMarker(Character)} to set the comment marker written at the start of each comment line.
+ *
+ *
+ * If the comment marker is not set, then the header comments are ignored.
+ *
+ *
+ * For example:
+ *
+ *
+ *
+ * builder.setCommentMarker('#').setHeaderComments("Generated by Apache Commons CSV", Instant.ofEpochMilli(0).toString());
+ *
+ * This method keeps a copy of the input array.
+ *
+ *
+ * @param headerComments the headerComments which will be printed by the Printer before the CSV data.
+ * @return This instance.
+ */
+ public Builder setHeaderComments(final String... headerComments) {
+ this.headerComments = CSVFormat.clone(headerComments);
+ return this;
+ }
+
+ /**
+ * Sets the empty line skipping behavior, {@code true} to ignore the empty lines between the records, {@code false} to translate empty lines to empty
+ * records.
+ *
+ * @param ignoreEmptyLines the empty line skipping behavior, {@code true} to ignore the empty lines between the records, {@code false} to translate
+ * empty lines to empty records.
+ * @return This instance.
+ */
+ public Builder setIgnoreEmptyLines(final boolean ignoreEmptyLines) {
+ this.ignoreEmptyLines = ignoreEmptyLines;
+ return this;
+ }
+
+ /**
+ * Sets the parser case mapping behavior, {@code true} to access name/values, {@code false} to leave the mapping as is.
+ *
+ * @param ignoreHeaderCase the case mapping behavior, {@code true} to access name/values, {@code false} to leave the mapping as is.
+ * @return This instance.
+ */
+ public Builder setIgnoreHeaderCase(final boolean ignoreHeaderCase) {
+ this.ignoreHeaderCase = ignoreHeaderCase;
+ return this;
+ }
+
+ /**
+ * Sets the parser trimming behavior, {@code true} to remove the surrounding spaces, {@code false} to leave the spaces as is.
+ *
+ * @param ignoreSurroundingSpaces the parser trimming behavior, {@code true} to remove the surrounding spaces, {@code false} to leave the spaces as is.
+ * @return This instance.
+ */
+ public Builder setIgnoreSurroundingSpaces(final boolean ignoreSurroundingSpaces) {
+ this.ignoreSurroundingSpaces = ignoreSurroundingSpaces;
+ return this;
+ }
+
+ /**
+ * Sets whether reading end-of-file is allowed even when input is malformed, helps Excel compatibility.
+ *
+ * @param lenientEof whether reading end-of-file is allowed even when input is malformed, helps Excel compatibility.
+ * @return This instance.
+ * @since 1.11.0
+ */
+ public Builder setLenientEof(final boolean lenientEof) {
+ this.lenientEof = lenientEof;
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of rows to process, excluding the header row.
+ *
+ * Values less than or equal to 0 mean no limit.
+ *
+ *
+ * @param maxRows the maximum number of rows to process, excluding the header row.
+ * @return This instance.
+ * @since 1.14.0
+ */
+ public Builder setMaxRows(final long maxRows) {
+ this.maxRows = maxRows;
+ return this;
+ }
+
+ /**
+ * Sets the String to convert to and from {@code null}. No substitution occurs if {@code null}.
+ *
+ *
+ *
Reading: Converts strings equal to the given {@code nullString} to {@code null} when reading records.
+ *
Writing: Writes {@code null} as the given {@code nullString} when writing records.
+ *
+ *
+ * @param nullString the String to convert to and from {@code null}. No substitution occurs if {@code null}.
+ * @return This instance.
+ */
+ public Builder setNullString(final String nullString) {
+ this.nullString = nullString;
+ return setQuotedNullString();
+ }
+
+ /**
+ * Sets the quote character.
+ *
+ * @param quoteCharacter the quote character.
+ * @return This instance.
+ */
+ public Builder setQuote(final char quoteCharacter) {
+ setQuote(Character.valueOf(quoteCharacter));
+ return this;
+ }
+
+ /**
+ * Sets the quote character, use {@code null} to disable.
+ *
+ * @param quoteCharacter the quote character, use {@code null} to disable.
+ * @return This instance.
+ */
+ public Builder setQuote(final Character quoteCharacter) {
+ if (isLineBreak(quoteCharacter)) {
+ throw new IllegalArgumentException("The quoteCharacter cannot be a line break");
+ }
+ this.quoteCharacter = quoteCharacter;
+ return setQuotedNullString();
+ }
+
+ private Builder setQuotedNullString() {
+ final Character quote = quoteCharacter != null ? quoteCharacter : Constants.DOUBLE_QUOTE_CHAR;
+ this.quotedNullString = quote + nullString + quote;
+ return this;
+ }
+
+ /**
+ * Sets the quote policy to use for output.
+ *
+ * @param quoteMode the quote policy to use for output.
+ * @return This instance.
+ */
+ public Builder setQuoteMode(final QuoteMode quoteMode) {
+ this.quoteMode = quoteMode;
+ return this;
+ }
+
+ /**
+ * Sets the record separator to use for output.
+ *
+ *
+ * Note: This setting is only used during printing and does not affect parsing. Parsing currently only works for inputs with '\n', '\r'
+ * and "\r\n"
+ *
+ *
+ * @param recordSeparator the record separator to use for output.
+ * @return This instance.
+ */
+ public Builder setRecordSeparator(final char recordSeparator) {
+ this.recordSeparator = String.valueOf(recordSeparator);
+ return this;
+ }
+
+ /**
+ * Sets the record separator to use for output.
+ *
+ *
+ * Note: This setting is only used during printing and does not affect parsing. Parsing currently only works for inputs with '\n', '\r'
+ * and "\r\n"
+ *
+ *
+ * @param recordSeparator the record separator to use for output.
+ * @return This instance.
+ */
+ public Builder setRecordSeparator(final String recordSeparator) {
+ this.recordSeparator = recordSeparator;
+ return this;
+ }
+
+ /**
+ * Sets whether to skip the header record.
+ *
+ * @param skipHeaderRecord whether to skip the header record.
+ * @return This instance.
+ */
+ public Builder setSkipHeaderRecord(final boolean skipHeaderRecord) {
+ this.skipHeaderRecord = skipHeaderRecord;
+ return this;
+ }
+
+ /**
+ * Sets whether reading trailing data is allowed in records, helps Excel compatibility.
+ *
+ * @param trailingData whether reading trailing data is allowed in records, helps Excel compatibility.
+ * @return This instance.
+ * @since 1.11.0
+ */
+ public Builder setTrailingData(final boolean trailingData) {
+ this.trailingData = trailingData;
+ return this;
+ }
+
+ /**
+ * Sets whether to add a trailing delimiter.
+ *
+ *
+ * When writing, a delimiter is appended after the last value of each record. When reading, the empty field
+ * that such a trailing delimiter produces is dropped so the output round-trips back to the original record;
+ * a quoted empty trailing field ({@code ""}) is a real value rather than a trailing delimiter and is kept.
+ *
+ *
+ * This is unrelated to {@link #setTrailingData(boolean) trailing data}, which controls whether characters
+ * after the closing quote of an encapsulated value are tolerated when reading.
+ *
+ *
+ * @param trailingDelimiter whether to add a trailing delimiter.
+ * @return This instance.
+ */
+ public Builder setTrailingDelimiter(final boolean trailingDelimiter) {
+ this.trailingDelimiter = trailingDelimiter;
+ return this;
+ }
+
+
+ /**
+ * Sets whether to trim leading and trailing blanks.
+ *
+ * @param trim whether to trim leading and trailing blanks.
+ * @return This instance.
+ */
+ public Builder setTrim(final boolean trim) {
+ this.trim = trim;
+ return this;
+ }
+ }
+
+ /**
+ * Enumerates predefines formats.
*
* @since 1.2
*/
public enum Predefined {
/**
+ * The DEFAULT predefined format.
+ *
* @see CSVFormat#DEFAULT
*/
- Default(CSVFormat.DEFAULT),
+ Default(DEFAULT),
/**
+ * The EXCEL predefined format.
+ *
* @see CSVFormat#EXCEL
*/
- Excel(CSVFormat.EXCEL),
+ Excel(EXCEL),
/**
+ * The INFORMIX_UNLOAD predefined format.
+ *
* @see CSVFormat#INFORMIX_UNLOAD
* @since 1.3
*/
- InformixUnload(CSVFormat.INFORMIX_UNLOAD),
+ InformixUnload(INFORMIX_UNLOAD),
/**
+ * The INFORMIX_UNLOAD_CSV predefined format.
+ *
* @see CSVFormat#INFORMIX_UNLOAD_CSV
* @since 1.3
*/
- InformixUnloadCsv(CSVFormat.INFORMIX_UNLOAD_CSV),
+ InformixUnloadCsv(INFORMIX_UNLOAD_CSV),
/**
+ * The MONGODB_CSV predefined format.
+ *
* @see CSVFormat#MONGODB_CSV
* @since 1.7
*/
- MongoDBCsv(CSVFormat.MONGODB_CSV),
+ MongoDBCsv(MONGODB_CSV),
/**
+ * The MONGODB_TSV predefined format.
+ *
* @see CSVFormat#MONGODB_TSV
* @since 1.7
*/
- MongoDBTsv(CSVFormat.MONGODB_TSV),
+ MongoDBTsv(MONGODB_TSV),
/**
+ * The MYSQL predefined format.
+ *
* @see CSVFormat#MYSQL
*/
- MySQL(CSVFormat.MYSQL),
+ MySQL(MYSQL),
/**
+ * The ORACLE predefined format.
+ *
* @see CSVFormat#ORACLE
*/
- Oracle(CSVFormat.ORACLE),
+ Oracle(ORACLE),
/**
+ * The POSTGRESQL_CSV predefined format.
+ *
* @see CSVFormat#POSTGRESQL_CSV
* @since 1.5
*/
- PostgreSQLCsv(CSVFormat.POSTGRESQL_CSV),
+ PostgreSQLCsv(POSTGRESQL_CSV),
/**
- * @see CSVFormat#POSTGRESQL_CSV
+ * The POSTGRESQL_TEXT predefined format.
+ *
+ * @see CSVFormat#POSTGRESQL_TEXT
*/
- PostgreSQLText(CSVFormat.POSTGRESQL_TEXT),
+ PostgreSQLText(POSTGRESQL_TEXT),
/**
+ * The RFC4180 predefined format.
+ *
* @see CSVFormat#RFC4180
*/
RFC4180(CSVFormat.RFC4180),
/**
+ * The TDF predefined format.
+ *
* @see CSVFormat#TDF
*/
TDF(CSVFormat.TDF);
@@ -253,157 +1030,173 @@ public CSVFormat getFormat() {
* Standard Comma Separated Value format, as for {@link #RFC4180} but allowing empty lines.
*
*
*
* @see Predefined#Default
+ * @see DuplicateHeaderMode#ALLOW_ALL
*/
- public static final CSVFormat DEFAULT = new CSVFormat(COMMA, DOUBLE_QUOTE_CHAR, null, null, null, false, true, CRLF,
- null, null, null, false, false, false, false, false, false);
+ public static final CSVFormat DEFAULT = new CSVFormat(Builder.create());
/**
- * Excel file format (using a comma as the value delimiter). Note that the actual value delimiter used by Excel is
- * locale dependent, it might be necessary to customize this format to accommodate to your regional settings.
+ * Microsoft Excel file
+ * format (using a comma as the value delimiter). Note that the actual value delimiter used by Excel is locale-dependent, it might be necessary to customize
+ * this format to accommodate your regional settings.
*
*
* For example for parsing or generating a CSV file on a French system the following format will be used:
*
- * Note: This is currently like {@link #RFC4180} plus {@link #withAllowMissingColumnNames(boolean)
- * withAllowMissingColumnNames(true)} and {@link #withIgnoreEmptyLines(boolean) withIgnoreEmptyLines(false)}.
+ * Note: This is currently like {@link #RFC4180} plus {@link Builder#setAllowMissingColumnNames(boolean) Builder#setAllowMissingColumnNames(true)} and
+ * {@link Builder#setIgnoreEmptyLines(boolean) Builder#setIgnoreEmptyLines(false)}.
*
*
* @see Predefined#Excel
+ * @see DuplicateHeaderMode#ALLOW_ALL
+ * @see Microsoft Excel
+ *
*/
// @formatter:off
- public static final CSVFormat EXCEL = DEFAULT
- .withIgnoreEmptyLines(false)
- .withAllowMissingColumnNames();
+ public static final CSVFormat EXCEL = DEFAULT.builder()
+ .setIgnoreEmptyLines(false)
+ .setAllowMissingColumnNames(true)
+ .setTrailingData(true)
+ .setLenientEof(true)
+ .get();
// @formatter:on
/**
- * Default Informix CSV UNLOAD format used by the {@code UNLOAD TO file_name} operation.
+ * Default Informix CSV UNLOAD
+ * format used by the {@code UNLOAD TO file_name} operation.
*
*
- * This is a comma-delimited format with a LF character as the line separator. Values are not quoted and special
- * characters are escaped with {@code '\'}. The default NULL string is {@code "\\N"}.
+ * This is a comma-delimited format with an LF character as the line separator. Values are not quoted and special characters are escaped with {@code '\'}.
+ * The default NULL string is {@code "\\N"}.
*
*
*
- * Settings are:
+ * The {@link Builder} settings are the {@link #DEFAULT} with:
*
*
* @see Predefined#MySQL
- * @see
- * http://www.ibm.com/support/knowledgecenter/SSBJG3_2.5.0/com.ibm.gen_busug.doc/c_fgl_InOutSql_UNLOAD.htm
+ * @see Informix CSV UNLOAD
* @since 1.3
*/
// @formatter:off
- public static final CSVFormat INFORMIX_UNLOAD = DEFAULT
- .withDelimiter(PIPE)
- .withEscape(BACKSLASH)
- .withQuote(DOUBLE_QUOTE_CHAR)
- .withRecordSeparator(LF);
+ public static final CSVFormat INFORMIX_UNLOAD = DEFAULT.builder()
+ .setDelimiter(Constants.PIPE)
+ .setEscape(Constants.BACKSLASH)
+ .setQuote(Constants.DOUBLE_QUOTE_CHAR)
+ .setRecordSeparator(Constants.LF)
+ .get();
// @formatter:on
/**
- * Default Informix CSV UNLOAD format used by the {@code UNLOAD TO file_name} operation (escaping is disabled.)
+ * Default Informix CSV UNLOAD
+ * format used by the {@code UNLOAD TO file_name} operation (escaping is disabled.)
*
*
- * This is a comma-delimited format with a LF character as the line separator. Values are not quoted and special
- * characters are escaped with {@code '\'}. The default NULL string is {@code "\\N"}.
+ * This is a comma-delimited format with an LF character as the line separator. Values are not quoted and special characters are escaped with {@code '\'}.
+ * The default NULL string is {@code "\\N"}.
*
*
*
- * Settings are:
+ * The {@link Builder} settings are the {@link #DEFAULT} with:
*
*
* @see Predefined#MySQL
- * @see
+ * @see
* http://www.ibm.com/support/knowledgecenter/SSBJG3_2.5.0/com.ibm.gen_busug.doc/c_fgl_InOutSql_UNLOAD.htm
* @since 1.3
*/
// @formatter:off
- public static final CSVFormat INFORMIX_UNLOAD_CSV = DEFAULT
- .withDelimiter(COMMA)
- .withQuote(DOUBLE_QUOTE_CHAR)
- .withRecordSeparator(LF);
+ public static final CSVFormat INFORMIX_UNLOAD_CSV = DEFAULT.builder()
+ .setDelimiter(Constants.COMMA)
+ .setQuote(Constants.DOUBLE_QUOTE_CHAR)
+ .setRecordSeparator(Constants.LF)
+ .get();
// @formatter:on
/**
* Default MongoDB CSV format used by the {@code mongoexport} operation.
*
- * Parsing is not supported yet.
+ * Parsing is not supported yet.
*
*
*
- * This is a comma-delimited format. Values are double quoted only if needed and special characters are escaped with
- * {@code '"'}. A header line with field names is expected.
+ * This is a comma-delimited format. Values are double quoted only if needed and special characters are escaped with {@code '"'}. A header line with field
+ * names is expected.
*
- *
*
- * Settings are:
+ * As of 2024-04-05, the MongoDB documentation for {@code mongoimport} states:
+ *
+ *
The csv parser accepts that data that complies with RFC RFC-4180. As a result, backslashes are
+ * not a valid escape character. If you use double-quotes to enclose fields in the CSV data, you must escape internal double-quote marks by prepending
+ * another double-quote.
+ *
+ * The {@link Builder} settings are the {@link #DEFAULT} with:
*
*
* @see Predefined#MongoDBCsv
+ * @see QuoteMode#ALL_NON_NULL
* @see MongoDB mongoexport command
* documentation
* @since 1.7
*/
// @formatter:off
- public static final CSVFormat MONGODB_TSV = DEFAULT
- .withDelimiter(TAB)
- .withEscape(DOUBLE_QUOTE_CHAR)
- .withQuote(DOUBLE_QUOTE_CHAR)
- .withQuoteMode(QuoteMode.MINIMAL)
- .withSkipHeaderRecord(false);
+ public static final CSVFormat MONGODB_TSV = DEFAULT.builder()
+ .setDelimiter(Constants.TAB)
+ .setEscape(Constants.DOUBLE_QUOTE_CHAR)
+ .setQuote(Constants.DOUBLE_QUOTE_CHAR)
+ .setQuoteMode(QuoteMode.MINIMAL)
+ .setSkipHeaderRecord(false)
+ .get();
// @formatter:off
/**
- * Default MySQL format used by the {@code SELECT INTO OUTFILE} and {@code LOAD DATA INFILE} operations.
+ * Default MySQL
+ * format used by the {@code SELECT INTO OUTFILE} and {@code LOAD DATA INFILE} operations.
*
*
- * This is a tab-delimited format with a LF character as the line separator. Values are not quoted and special
+ * This is a tab-delimited format with an LF character as the line separator. Values are not quoted and special
* characters are escaped with {@code '\'}. The default NULL string is {@code "\\N"}.
*
*
*
- * Settings are:
+ * The {@link Builder} settings are the {@link #DEFAULT} with:
*
*
* @see Predefined#MySQL
- * @see http://dev.mysql.com/doc/refman/5.1/en/load
- * -data.html
+ * @see QuoteMode#ALL_NON_NULL
+ * @see MySQL
*/
// @formatter:off
- public static final CSVFormat MYSQL = DEFAULT
- .withDelimiter(TAB)
- .withEscape(BACKSLASH)
- .withIgnoreEmptyLines(false)
- .withQuote(null)
- .withRecordSeparator(LF)
- .withNullString("\\N")
- .withQuoteMode(QuoteMode.ALL_NON_NULL);
+ public static final CSVFormat MYSQL = DEFAULT.builder()
+ .setDelimiter(Constants.TAB)
+ .setEscape(Constants.BACKSLASH)
+ .setIgnoreEmptyLines(false)
+ .setQuote(null)
+ .setRecordSeparator(Constants.LF)
+ .setNullString(Constants.SQL_NULL_STRING)
+ .setQuoteMode(QuoteMode.ALL_NON_NULL)
+ .get();
// @formatter:off
/**
- * Default Oracle format used by the SQL*Loader utility.
+ * Default
+ * Oracle
+ * format used by the SQL*Loader utility.
*
*
- * This is a comma-delimited format with the system line separator character as the record separator.Values are
+ * This is a comma-delimited format with the system line separator character as the record separator. Values are
* double quoted when needed and special characters are escaped with {@code '"'}. The default NULL string is
* {@code ""}. Values are trimmed.
*
*
*
- * Settings are:
+ * The {@link Builder} settings are the {@link #DEFAULT} with:
*
*
- *
{@code withDelimiter(',') // default is {@code FIELDS TERMINATED BY ','}}
- *
{@code withEscape('\\')}
- *
{@code withIgnoreEmptyLines(false)}
- *
{@code withQuote('"') // default is {@code OPTIONALLY ENCLOSED BY '"'}}
- *
{@code withNullString("\\N")}
- *
{@code withTrim()}
- *
{@code withSystemRecordSeparator()}
- *
{@code withQuoteMode(QuoteMode.MINIMAL)}
+ *
{@link Builder#setDelimiter(char) setDelimiter}{@code (',')} // default is {@code FIELDS TERMINATED BY ','}}
*
* @see Predefined#Oracle
- * @see Oracle CSV Format Specification
+ * @see QuoteMode#MINIMAL
+ * @see Oracle CSV Format Specification
* @since 1.6
*/
// @formatter:off
- public static final CSVFormat ORACLE = DEFAULT
- .withDelimiter(COMMA)
- .withEscape(BACKSLASH)
- .withIgnoreEmptyLines(false)
- .withQuote(DOUBLE_QUOTE_CHAR)
- .withNullString("\\N")
- .withTrim()
- .withSystemRecordSeparator()
- .withQuoteMode(QuoteMode.MINIMAL);
+ public static final CSVFormat ORACLE = DEFAULT.builder()
+ .setDelimiter(Constants.COMMA)
+ .setEscape(Constants.BACKSLASH)
+ .setIgnoreEmptyLines(false)
+ .setQuote(Constants.DOUBLE_QUOTE_CHAR)
+ .setNullString(Constants.SQL_NULL_STRING)
+ .setTrim(true)
+ .setRecordSeparator(System.lineSeparator())
+ .setQuoteMode(QuoteMode.MINIMAL)
+ .get();
// @formatter:off
/**
- * Default PostgreSQL CSV format used by the {@code COPY} operation.
+ * Default PostgreSQL CSV format used by the {@code COPY} operation.
*
*
- * This is a comma-delimited format with a LF character as the line separator. Values are double quoted and special
- * characters are escaped with {@code '"'}. The default NULL string is {@code ""}.
+ * This is a comma-delimited format with an LF character as the line separator. Values are double quoted and special
+ * characters are not escaped. The default NULL string is {@code ""}.
*
*
*
- * Settings are:
+ * The {@link Builder} settings are the {@link #DEFAULT} with:
*
*
* @see Predefined#MySQL
- * @see PostgreSQL COPY command
- * documentation
+ * @see QuoteMode#ALL_NON_NULL
+ * @see PostgreSQL CSV
* @since 1.5
*/
// @formatter:off
- public static final CSVFormat POSTGRESQL_CSV = DEFAULT
- .withDelimiter(COMMA)
- .withEscape(DOUBLE_QUOTE_CHAR)
- .withIgnoreEmptyLines(false)
- .withQuote(DOUBLE_QUOTE_CHAR)
- .withRecordSeparator(LF)
- .withNullString(EMPTY)
- .withQuoteMode(QuoteMode.ALL_NON_NULL);
+ public static final CSVFormat POSTGRESQL_CSV = DEFAULT.builder()
+ .setDelimiter(Constants.COMMA)
+ .setEscape(null)
+ .setIgnoreEmptyLines(false)
+ .setQuote(Constants.DOUBLE_QUOTE_CHAR)
+ .setRecordSeparator(Constants.LF)
+ .setNullString(Constants.EMPTY)
+ .setQuoteMode(QuoteMode.ALL_NON_NULL)
+ .get();
// @formatter:off
/**
- * Default PostgreSQL text format used by the {@code COPY} operation.
+ * Default PostgreSQL Text format used by the {@code COPY} operation.
*
*
- * This is a tab-delimited format with a LF character as the line separator. Values are double quoted and special
- * characters are escaped with {@code '"'}. The default NULL string is {@code "\\N"}.
+ * This is a tab-delimited format with an LF character as the line separator. Values are not quoted and special
+ * characters are escaped with {@code '\\'}. The default NULL string is {@code "\\N"}.
*
*
*
- * Settings are:
+ * The {@link Builder} settings are the {@link #DEFAULT} with:
*
*
* @see Predefined#TDF
+ * @see TDF
*/
// @formatter:off
- public static final CSVFormat TDF = DEFAULT
- .withDelimiter(TAB)
- .withIgnoreSurroundingSpaces();
+ public static final CSVFormat TDF = DEFAULT.builder()
+ .setDelimiter(Constants.TAB)
+ .setIgnoreSurroundingSpaces(true)
+ .get();
// @formatter:on
/**
- * Returns true if the given character is a line break character.
+ * Null-safe clone of an array.
*
- * @param c
- * the character to check
+ * @param The array element type.
+ * @param values the source array
+ * @return the cloned array.
+ */
+ @SafeVarargs
+ static T[] clone(final T... values) {
+ return values == null ? null : values.clone();
+ }
+
+ /**
+ * Returns true if the given string contains the search char.
*
- * @return true if c is a line break character
+ * @param source the string to check.
+ * @param searchCh the character to search.
+ * @return true if {@code c} contains a line break character
*/
- private static boolean isLineBreak(final char c) {
- return c == LF || c == CR;
+ private static boolean contains(final String source, final char searchCh) {
+ return Objects.requireNonNull(source, "source").indexOf(searchCh) >= 0;
+ }
+
+ /**
+ * Returns true if the given string contains a line break character.
+ *
+ * @param source the string to check.
+ * @return true if {@code c} contains a line break character.
+ */
+ private static boolean containsLineBreak(final String source) {
+ return contains(source, Constants.CR) || contains(source, Constants.LF);
+ }
+
+ /**
+ * Creates a null-safe copy of the given instance.
+ *
+ * @return a copy of the given instance or null if the input is null.
+ */
+ static CSVFormat copy(final CSVFormat format) {
+ return format != null ? format.copy() : null;
+ }
+
+ static boolean isBlank(final String value) {
+ return value == null || value.trim().isEmpty();
}
/**
* Returns true if the given character is a line break character.
*
- * @param c
- * the character to check, may be null
+ * @param c the character to check.
+ * @return true if {@code c} is a line break character.
+ */
+ private static boolean isLineBreak(final char c) {
+ return c == Constants.LF || c == Constants.CR;
+ }
+
+ /**
+ * Returns true if the given character is a line break character.
*
- * @return true if c is a line break character (and not null)
+ * @param c the character to check, may be null.
+ * @return true if {@code c} is a line break character (and not null).
*/
private static boolean isLineBreak(final Character c) {
- return c != null && isLineBreak(c.charValue());
+ return c != null && isLineBreak(c.charValue()); // Explicit unboxing is intentional
+ }
+
+ /** Same test as in as {@link String#trim()}. */
+ private static boolean isTrimChar(final char ch) {
+ return ch <= Constants.SP;
+ }
+
+ /** Same test as in as {@link String#trim()}. */
+ private static boolean isTrimChar(final CharSequence charSequence, final int pos) {
+ return isTrimChar(charSequence.charAt(pos));
}
/**
* Creates a new CSV format with the specified delimiter.
*
*
- * Use this method if you want to create a CSVFormat from scratch. All fields but the delimiter will be initialized
- * with null/false.
+ * Use this method if you want to create a CSVFormat from scratch. All fields but the delimiter will be initialized with null/false.
*
*
- * @param delimiter
- * the char used for value separation, must not be a line break character
+ * @param delimiter the char used for value separation, must not be a line break character
* @return a new CSV format.
- * @throws IllegalArgumentException
- * if the delimiter is a line break character
- *
+ * @throws IllegalArgumentException if the delimiter is a line break character
* @see #DEFAULT
* @see #RFC4180
* @see #MYSQL
@@ -670,15 +1522,39 @@ private static boolean isLineBreak(final Character c) {
* @see #TDF
*/
public static CSVFormat newFormat(final char delimiter) {
- return new CSVFormat(delimiter, null, null, null, null, false, false, null, null, null, null, false, false,
- false, false, false, false);
+ return new CSVFormat(new Builder().setDelimiter(delimiter));
+ }
+
+ static String[] toStringArray(final Object[] values) {
+ if (values == null) {
+ return null;
+ }
+ final String[] strings = new String[values.length];
+ Arrays.setAll(strings, i -> Objects.toString(values[i], null));
+ return strings;
+ }
+
+ static CharSequence trim(final CharSequence charSequence) {
+ if (charSequence instanceof String) {
+ return ((String) charSequence).trim();
+ }
+ final int count = charSequence.length();
+ int len = count;
+ int pos = 0;
+
+ while (pos < len && isTrimChar(charSequence, pos)) {
+ pos++;
+ }
+ while (pos < len && isTrimChar(charSequence, len - 1)) {
+ len--;
+ }
+ return pos > 0 || len < count ? charSequence.subSequence(pos, len) : charSequence;
}
/**
* Gets one of the predefined formats from {@link CSVFormat.Predefined}.
*
- * @param format
- * name
+ * @param format name
* @return one of the predefined formats
* @since 1.2
*/
@@ -686,207 +1562,204 @@ public static CSVFormat valueOf(final String format) {
return CSVFormat.Predefined.valueOf(format).getFormat();
}
+ /** How duplicate headers are handled. */
+ private final DuplicateHeaderMode duplicateHeaderMode;
+
+ /** Whether missing column names are allowed when parsing the header line. */
private final boolean allowMissingColumnNames;
- private final Character commentMarker; // null if commenting is disabled
+ /** Whether to flush on close. */
+ private final boolean autoFlush;
+
+ /** Set to null if commenting is disabled. */
+ private final Character commentMarker;
- private final char delimiter;
+ /** The character delimiting the values (typically ";", "," or "\t"). */
+ private final String delimiter;
- private final Character escapeCharacter; // null if escaping is disabled
+ /** Set to null if escaping is disabled. */
+ private final Character escapeCharacter;
- private final String[] header; // array of header column names
+ /** Array of header column names. */
+ private final String[] headers;
- private final String[] headerComments; // array of header comment lines
+ /** Array of header comment lines. */
+ private final String[] headerComments;
+ /** Whether empty lines between records are ignored when parsing input. */
private final boolean ignoreEmptyLines;
- private final boolean ignoreHeaderCase; // should ignore header names case
+ /** Should ignore header names case. */
+ private final boolean ignoreHeaderCase;
- private final boolean ignoreSurroundingSpaces; // Should leading/trailing spaces be ignored around values?
+ /** Should leading/trailing spaces be ignored around values?. */
+ private final boolean ignoreSurroundingSpaces;
- private final String nullString; // the string to be used for null values
+ /** The string to be used for null values. */
+ private final String nullString;
- private final Character quoteCharacter; // null if quoting is disabled
+ /** Set to null if quoting is disabled. */
+ private final Character quoteCharacter;
+ /** Set to {@code quoteCharacter + nullString + quoteCharacter} */
private final String quotedNullString;
+ /** The quote policy output fields. */
private final QuoteMode quoteMode;
- private final String recordSeparator; // for outputs
+ /** For output. */
+ private final String recordSeparator;
+ /** Whether to skip the header record. */
private final boolean skipHeaderRecord;
+ /** Whether reading end-of-file is allowed even when input is malformed, helps Excel compatibility. */
+ private final boolean lenientEof;
+
+ /** Whether reading trailing data is allowed in records, helps Excel compatibility. */
+ private final boolean trailingData;
+
+ /** Whether to add a trailing delimiter. */
private final boolean trailingDelimiter;
+ /** Whether to trim leading and trailing blanks. */
private final boolean trim;
- private final boolean autoFlush;
+ /** The maximum number of rows to process, excluding the header row. */
+ private final long maxRows;
+
+ private CSVFormat(final Builder builder) {
+ this.allowMissingColumnNames = builder.allowMissingColumnNames;
+ this.autoFlush = builder.autoFlush;
+ this.commentMarker = builder.commentMarker;
+ this.delimiter = builder.delimiter;
+ this.duplicateHeaderMode = builder.duplicateHeaderMode;
+ this.escapeCharacter = builder.escapeCharacter;
+ this.headerComments = builder.headerComments;
+ this.headers = builder.headers;
+ this.ignoreEmptyLines = builder.ignoreEmptyLines;
+ this.ignoreHeaderCase = builder.ignoreHeaderCase;
+ this.ignoreSurroundingSpaces = builder.ignoreSurroundingSpaces;
+ this.lenientEof = builder.lenientEof;
+ this.maxRows = builder.maxRows;
+ this.nullString = builder.nullString;
+ this.quoteCharacter = builder.quoteCharacter;
+ this.quoteMode = builder.quoteMode;
+ this.quotedNullString = builder.quotedNullString;
+ this.recordSeparator = builder.recordSeparator;
+ this.skipHeaderRecord = builder.skipHeaderRecord;
+ this.trailingData = builder.trailingData;
+ this.trailingDelimiter = builder.trailingDelimiter;
+ this.trim = builder.trim;
+ validate();
+ }
+
+ private void append(final char c, final Appendable appendable) throws IOException {
+ // try {
+ appendable.append(c);
+ // } catch (final IOException e) {
+ // throw new UncheckedIOException(e);
+ // }
+ }
+
+ private void append(final CharSequence csq, final Appendable appendable) throws IOException {
+ // try {
+ appendable.append(csq);
+ // } catch (final IOException e) {
+ // throw new UncheckedIOException(e);
+ // }
+ }
/**
- * Creates a customized CSV format.
- *
- * @param delimiter
- * the char used for value separation, must not be a line break character
- * @param quoteChar
- * the Character used as value encapsulation marker, may be {@code null} to disable
- * @param quoteMode
- * the quote mode
- * @param commentStart
- * the Character used for comment identification, may be {@code null} to disable
- * @param escape
- * the Character used to escape special characters in values, may be {@code null} to disable
- * @param ignoreSurroundingSpaces
- * {@code true} when whitespaces enclosing values should be ignored
- * @param ignoreEmptyLines
- * {@code true} when the parser should skip empty lines
- * @param recordSeparator
- * the line separator to use for output
- * @param nullString
- * the line separator to use for output
- * @param headerComments
- * the comments to be printed by the Printer before the actual CSV data
- * @param header
- * the header
- * @param skipHeaderRecord
- * TODO
- * @param allowMissingColumnNames
- * TODO
- * @param ignoreHeaderCase
- * TODO
- * @param trim
- * TODO
- * @param trailingDelimiter
- * TODO
- * @param autoFlush
- * @throws IllegalArgumentException
- * if the delimiter is a line break character
- */
- private CSVFormat(final char delimiter, final Character quoteChar, final QuoteMode quoteMode,
- final Character commentStart, final Character escape, final boolean ignoreSurroundingSpaces,
- final boolean ignoreEmptyLines, final String recordSeparator, final String nullString,
- final Object[] headerComments, final String[] header, final boolean skipHeaderRecord,
- final boolean allowMissingColumnNames, final boolean ignoreHeaderCase, final boolean trim,
- final boolean trailingDelimiter, final boolean autoFlush) {
- this.delimiter = delimiter;
- this.quoteCharacter = quoteChar;
- this.quoteMode = quoteMode;
- this.commentMarker = commentStart;
- this.escapeCharacter = escape;
- this.ignoreSurroundingSpaces = ignoreSurroundingSpaces;
- this.allowMissingColumnNames = allowMissingColumnNames;
- this.ignoreEmptyLines = ignoreEmptyLines;
- this.recordSeparator = recordSeparator;
- this.nullString = nullString;
- this.headerComments = toStringArray(headerComments);
- this.header = header == null ? null : header.clone();
- this.skipHeaderRecord = skipHeaderRecord;
- this.ignoreHeaderCase = ignoreHeaderCase;
- this.trailingDelimiter = trailingDelimiter;
- this.trim = trim;
- this.autoFlush = autoFlush;
- this.quotedNullString = quoteCharacter + nullString + quoteCharacter;
- validate();
+ * Creates a new Builder for this instance.
+ *
+ * @return a new Builder.
+ */
+ public Builder builder() {
+ return Builder.create(this);
}
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
+ /**
+ * Creates a copy of this instance.
+ *
+ * @return a copy of this instance.
+ */
+ CSVFormat copy() {
+ return builder().get();
+ }
- final CSVFormat other = (CSVFormat) obj;
- if (delimiter != other.delimiter) {
- return false;
- }
- if (quoteMode != other.quoteMode) {
- return false;
- }
- if (quoteCharacter == null) {
- if (other.quoteCharacter != null) {
- return false;
- }
- } else if (!quoteCharacter.equals(other.quoteCharacter)) {
- return false;
- }
- if (commentMarker == null) {
- if (other.commentMarker != null) {
- return false;
- }
- } else if (!commentMarker.equals(other.commentMarker)) {
- return false;
- }
- if (escapeCharacter == null) {
- if (other.escapeCharacter != null) {
- return false;
- }
- } else if (!escapeCharacter.equals(other.escapeCharacter)) {
- return false;
- }
- if (nullString == null) {
- if (other.nullString != null) {
- return false;
- }
- } else if (!nullString.equals(other.nullString)) {
- return false;
- }
- if (!Arrays.equals(header, other.header)) {
- return false;
- }
- if (ignoreSurroundingSpaces != other.ignoreSurroundingSpaces) {
- return false;
- }
- if (ignoreEmptyLines != other.ignoreEmptyLines) {
- return false;
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj) {
+ return true;
}
- if (skipHeaderRecord != other.skipHeaderRecord) {
+ if (obj == null) {
return false;
}
- if (recordSeparator == null) {
- if (other.recordSeparator != null) {
- return false;
- }
- } else if (!recordSeparator.equals(other.recordSeparator)) {
+ if (getClass() != obj.getClass()) {
return false;
}
- return true;
+ final CSVFormat other = (CSVFormat) obj;
+ return allowMissingColumnNames == other.allowMissingColumnNames && autoFlush == other.autoFlush &&
+ Objects.equals(commentMarker, other.commentMarker) && Objects.equals(delimiter, other.delimiter) &&
+ duplicateHeaderMode == other.duplicateHeaderMode && Objects.equals(escapeCharacter, other.escapeCharacter) &&
+ Arrays.equals(headerComments, other.headerComments) && Arrays.equals(headers, other.headers) &&
+ ignoreEmptyLines == other.ignoreEmptyLines && ignoreHeaderCase == other.ignoreHeaderCase &&
+ ignoreSurroundingSpaces == other.ignoreSurroundingSpaces && lenientEof == other.lenientEof && maxRows == other.maxRows &&
+ Objects.equals(nullString, other.nullString) && Objects.equals(quoteCharacter, other.quoteCharacter) && quoteMode == other.quoteMode &&
+ Objects.equals(quotedNullString, other.quotedNullString) && Objects.equals(recordSeparator, other.recordSeparator) &&
+ skipHeaderRecord == other.skipHeaderRecord && trailingData == other.trailingData && trailingDelimiter == other.trailingDelimiter &&
+ trim == other.trim;
+ }
+
+ private void escape(final char c, final Appendable appendable) throws IOException {
+ append(escapeCharacter.charValue(), appendable); // Explicit unboxing is intentional
+ append(c, appendable);
}
/**
- * Formats the specified values.
+ * Formats the specified values as a CSV record string.
*
- * @param values
- * the values to format
- * @return the formatted values
+ * @param values the values to format.
+ * @return the formatted values.
*/
public String format(final Object... values) {
+ return Uncheck.get(() -> format_(values));
+ }
+
+ private String format_(final Object... values) throws IOException {
final StringWriter out = new StringWriter();
- try (final CSVPrinter csvPrinter = new CSVPrinter(out, this)) {
+ try (CSVPrinter csvPrinter = new CSVPrinter(out, this)) {
csvPrinter.printRecord(values);
- return out.toString().trim();
- } catch (final IOException e) {
- // should not happen because a StringWriter does not do IO.
- throw new IllegalStateException(e);
+ final String res = out.toString();
+ final int len = recordSeparator != null ? res.length() - recordSeparator.length() : res.length();
+ return res.substring(0, len);
}
}
/**
- * Specifies whether missing column names are allowed when parsing the header line.
+ * Gets whether duplicate names are allowed in the headers.
+ *
+ * @return whether duplicate header names are allowed
+ * @since 1.7
+ * @deprecated Use {@link #getDuplicateHeaderMode()}.
+ */
+ @Deprecated
+ public boolean getAllowDuplicateHeaderNames() {
+ return duplicateHeaderMode == DuplicateHeaderMode.ALLOW_ALL;
+ }
+
+ /**
+ * Gets whether missing column names are allowed when parsing the header line.
*
- * @return {@code true} if missing column names are allowed when parsing the header line, {@code false} to throw an
- * {@link IllegalArgumentException}.
+ * @return {@code true} if missing column names are allowed when parsing the header line, {@code false} to throw an {@link IllegalArgumentException}.
*/
public boolean getAllowMissingColumnNames() {
return allowMissingColumnNames;
}
/**
- * Returns whether to flush on close.
+ * Gets whether to flush on close.
*
* @return whether to flush on close.
* @since 1.6
@@ -896,7 +1769,35 @@ public boolean getAutoFlush() {
}
/**
- * Returns the character marking the start of a line comment.
+ * Gets the comment marker character, {@code null} disables comments.
+ *
+ * The comment start character is only recognized at the start of a line.
+ *
+ *
+ * Comments are printed first, before headers.
+ *
+ *
+ * Use {@link Builder#setCommentMarker(char)} or {@link Builder#setCommentMarker(Character)} to set the comment marker written at the start of each comment
+ * line.
+ *
+ *
+ * If the comment marker is not set, then the header comments are ignored.
+ *
+ *
+ * For example:
+ *
+ *
+ *
+ * builder.setCommentMarker('#').setHeaderComments("Generated by Apache Commons CSV", Instant.ofEpochMilli(0));
+ *
*
* @return the comment start marker, may be {@code null}
*/
@@ -905,16 +1806,56 @@ public Character getCommentMarker() {
}
/**
- * Returns the character delimiting the values (typically ';', ',' or '\t').
+ * Gets the first character delimiting the values (typically ';', ',' or '\t').
*
- * @return the delimiter character
+ * @return the first delimiter character.
+ * @deprecated Use {@link #getDelimiterString()}.
*/
+ @Deprecated
public char getDelimiter() {
+ return delimiter.charAt(0);
+ }
+
+ /**
+ * Gets the character delimiting the values (typically ";", "," or "\t").
+ *
+ * @return the delimiter.
+ */
+ char[] getDelimiterCharArray() {
+ return delimiter.toCharArray();
+ }
+
+ /**
+ * Gets the character delimiting the values (typically ";", "," or "\t").
+ *
+ * @return the delimiter.
+ * @since 1.9.0
+ */
+ public String getDelimiterString() {
return delimiter;
}
/**
- * Returns the escape character.
+ * Gets how duplicate headers are handled.
+ *
+ * @return if duplicate header values are allowed, allowed conditionally, or disallowed.
+ * @since 1.10.0
+ */
+ public DuplicateHeaderMode getDuplicateHeaderMode() {
+ return duplicateHeaderMode;
+ }
+
+ /**
+ * Gets the escape character.
+ *
+ * @return the escape character, may be {@code 0}
+ */
+ char getEscapeChar() {
+ return escapeCharacter != null ? escapeCharacter.charValue() : 0; // Explicit unboxing is intentional
+ }
+
+ /**
+ * Gets the escape character.
*
* @return the escape character, may be {@code null}
*/
@@ -923,16 +1864,44 @@ public Character getEscapeCharacter() {
}
/**
- * Returns a copy of the header array.
+ * Gets a copy of the header array.
*
* @return a copy of the header array; {@code null} if disabled, the empty array if to be read from the file
*/
public String[] getHeader() {
- return header != null ? header.clone() : null;
+ return headers != null ? headers.clone() : null;
}
/**
- * Returns a copy of the header comment array.
+ * Gets a copy of the header comment array to write before the CSV data.
+ *
+ * This setting is ignored by the parser.
+ *
+ *
+ * Comments are printed first, before headers.
+ *
+ *
+ * Use {@link Builder#setCommentMarker(char)} or {@link Builder#setCommentMarker(Character)} to set the comment marker written at the start of each comment
+ * line.
+ *
+ *
+ * If the comment marker is not set, then the header comments are ignored.
+ *
+ *
+ * For example:
+ *
+ *
+ *
+ * builder.setCommentMarker('#').setHeaderComments("Generated by Apache Commons CSV", Instant.ofEpochMilli(0));
+ *
*
* @return a copy of the header comment array; {@code null} if disabled.
*/
@@ -941,19 +1910,18 @@ public String[] getHeaderComments() {
}
/**
- * Specifies whether empty lines between records are ignored when parsing input.
+ * Gets whether empty lines between records are ignored when parsing input.
*
- * @return {@code true} if empty lines between records are ignored, {@code false} if they are turned into empty
- * records.
+ * @return {@code true} if empty lines between records are ignored, {@code false} if they are turned into empty records.
*/
public boolean getIgnoreEmptyLines() {
return ignoreEmptyLines;
}
/**
- * Specifies whether header names will be accessed ignoring case.
+ * Gets whether header names will be accessed ignoring case when parsing input.
*
- * @return {@code true} if header names cases are ignored, {@code false} if they are case sensitive.
+ * @return {@code true} if header names cases are ignored, {@code false} if they are case-sensitive.
* @since 1.3
*/
public boolean getIgnoreHeaderCase() {
@@ -961,7 +1929,7 @@ public boolean getIgnoreHeaderCase() {
}
/**
- * Specifies whether spaces around values are ignored when parsing input.
+ * Gets whether spaces around values are ignored when parsing input.
*
* @return {@code true} if spaces around values are ignored, {@code false} if they are treated as part of the value.
*/
@@ -969,11 +1937,33 @@ public boolean getIgnoreSurroundingSpaces() {
return ignoreSurroundingSpaces;
}
+ /**
+ * Gets whether reading end-of-file is allowed even when input is malformed, helps Excel compatibility.
+ *
+ * @return whether reading end-of-file is allowed even when input is malformed, helps Excel compatibility.
+ * @since 1.11.0
+ */
+ public boolean getLenientEof() {
+ return lenientEof;
+ }
+
+ /**
+ * Gets the maximum number of rows to process, excluding the header row.
+ *
+ * Values less than or equal to 0 mean no limit.
+ *
+ *
+ * @return The maximum number of rows to process, excluding the header row.
+ * @since 1.14.0
+ */
+ public long getMaxRows() {
+ return maxRows;
+ }
+
/**
* Gets the String to convert to and from {@code null}.
*
- *
Reading: Converts strings equal to the given {@code nullString} to {@code null} when reading
- * records.
+ *
Reading: Converts strings equal to the given {@code nullString} to {@code null} when reading records.
*
Writing: Writes {@code null} as the given {@code nullString} when writing records.
*
*
@@ -984,7 +1974,7 @@ public String getNullString() {
}
/**
- * Returns the character used to encapsulate values containing special characters.
+ * Gets the character used to encapsulate values containing special characters.
*
* @return the quoteChar character, may be {@code null}
*/
@@ -993,7 +1983,7 @@ public Character getQuoteCharacter() {
}
/**
- * Returns the quote policy output fields.
+ * Gets the quote policy output fields.
*
* @return the quote policy
*/
@@ -1002,7 +1992,7 @@ public QuoteMode getQuoteMode() {
}
/**
- * Returns the record separator delimiting output records.
+ * Gets the record separator delimiting output records.
*
* @return the record separator
*/
@@ -1011,7 +2001,7 @@ public String getRecordSeparator() {
}
/**
- * Returns whether to skip the header record.
+ * Gets whether to skip the header record.
*
* @return whether to skip the header record.
*/
@@ -1020,7 +2010,27 @@ public boolean getSkipHeaderRecord() {
}
/**
- * Returns whether to add a trailing delimiter.
+ * Gets whether reading trailing data is allowed in records, helps Excel compatibility.
+ *
+ * @return whether reading trailing data is allowed in records, helps Excel compatibility.
+ * @since 1.11.0
+ */
+ public boolean getTrailingData() {
+ return trailingData;
+ }
+
+ /**
+ * Gets whether to add a trailing delimiter.
+ *
+ *
+ * When writing, a delimiter is appended after the last value of each record. When reading, the empty field
+ * that such a trailing delimiter produces is dropped so the output round-trips back to the original record;
+ * a quoted empty trailing field ({@code ""}) is a real value rather than a trailing delimiter and is kept.
+ *
+ *
+ * This is unrelated to {@link #getTrailingData() trailing data}, which controls whether characters after the
+ * closing quote of an encapsulated value are tolerated when reading.
+ *
*
* @return whether to add a trailing delimiter.
* @since 1.3
@@ -1030,7 +2040,7 @@ public boolean getTrailingDelimiter() {
}
/**
- * Returns whether to trim leading and trailing blanks.
+ * Gets whether to trim leading and trailing blanks. This is used by {@link #print(Object, Appendable, boolean)} Also by {CSVParser#addRecordValue(boolean)}
*
* @return whether to trim leading and trailing blanks.
*/
@@ -1042,24 +2052,16 @@ public boolean getTrim() {
public int hashCode() {
final int prime = 31;
int result = 1;
-
- result = prime * result + delimiter;
- result = prime * result + ((quoteMode == null) ? 0 : quoteMode.hashCode());
- result = prime * result + ((quoteCharacter == null) ? 0 : quoteCharacter.hashCode());
- result = prime * result + ((commentMarker == null) ? 0 : commentMarker.hashCode());
- result = prime * result + ((escapeCharacter == null) ? 0 : escapeCharacter.hashCode());
- result = prime * result + ((nullString == null) ? 0 : nullString.hashCode());
- result = prime * result + (ignoreSurroundingSpaces ? 1231 : 1237);
- result = prime * result + (ignoreHeaderCase ? 1231 : 1237);
- result = prime * result + (ignoreEmptyLines ? 1231 : 1237);
- result = prime * result + (skipHeaderRecord ? 1231 : 1237);
- result = prime * result + ((recordSeparator == null) ? 0 : recordSeparator.hashCode());
- result = prime * result + Arrays.hashCode(header);
+ result = prime * result + Arrays.hashCode(headerComments);
+ result = prime * result + Arrays.hashCode(headers);
+ result = prime * result + Objects.hash(allowMissingColumnNames, autoFlush, commentMarker, delimiter, duplicateHeaderMode, escapeCharacter,
+ ignoreEmptyLines, ignoreHeaderCase, ignoreSurroundingSpaces, lenientEof, maxRows, nullString, quoteCharacter, quoteMode, quotedNullString,
+ recordSeparator, skipHeaderRecord, trailingData, trailingDelimiter, trim);
return result;
}
/**
- * Specifies whether comments are supported by this format.
+ * Tests whether comments are supported by this format.
*
* Note that the comment introducer character is only recognized at the start of a line.
*
@@ -1070,7 +2072,33 @@ public boolean isCommentMarkerSet() {
}
/**
- * Returns whether escape are being processed.
+ * Tests whether the next characters constitute a delimiter
+ *
+ * @param ch0 the first char (index 0).
+ * @param charSeq the match char sequence
+ * @param startIndex where start to match
+ * @param delimiter the delimiter
+ * @param delimiterLength the delimiter length
+ * @return true if the match is successful
+ */
+ private boolean isDelimiter(final char ch0, final CharSequence charSeq, final int startIndex, final char[] delimiter, final int delimiterLength) {
+ if (ch0 != delimiter[0]) {
+ return false;
+ }
+ final int len = charSeq.length();
+ if (startIndex + delimiterLength > len) {
+ return false;
+ }
+ for (int i = 1; i < delimiterLength; i++) {
+ if (charSeq.charAt(startIndex + i) != delimiter[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Tests whether escapes are being processed.
*
* @return {@code true} if escapes are processed
*/
@@ -1079,7 +2107,7 @@ public boolean isEscapeCharacterSet() {
}
/**
- * Returns whether a nullString has been defined.
+ * Tests whether a null string has been defined.
*
* @return {@code true} if a nullString is defined
*/
@@ -1088,7 +2116,7 @@ public boolean isNullStringSet() {
}
/**
- * Returns whether a quoteChar has been defined.
+ * Tests whether a quoteChar has been defined.
*
* @return {@code true} if a quoteChar is defined
*/
@@ -1096,6 +2124,10 @@ public boolean isQuoteCharacterSet() {
return quoteCharacter != null;
}
+ IOStream limit(final IOStream stream) {
+ return useMaxRows() ? stream.limit(getMaxRows()) : stream;
+ }
+
/**
* Parses the specified content.
*
@@ -1103,14 +2135,13 @@ public boolean isQuoteCharacterSet() {
* See also the various static parse methods on {@link CSVParser}.
*
*
- * @param in
- * the input stream
+ * @param reader the input stream
* @return a parser over a stream of {@link CSVRecord}s.
- * @throws IOException
- * If an I/O error occurs
+ * @throws IOException If an I/O error occurs
+ * @throws CSVException Thrown on invalid input.
*/
- public CSVParser parse(final Reader in) throws IOException {
- return new CSVParser(in, this);
+ public CSVParser parse(final Reader reader) throws IOException {
+ return CSVParser.builder().setReader(reader).setFormat(this).get();
}
/**
@@ -1120,92 +2151,99 @@ public CSVParser parse(final Reader in) throws IOException {
* See also {@link CSVPrinter}.
*
*
- * @param out
- * the output.
+ * @param out the output.
* @return a printer to an output.
- * @throws IOException
- * thrown if the optional header cannot be printed.
+ * @throws IOException thrown if the optional header cannot be printed.
*/
public CSVPrinter print(final Appendable out) throws IOException {
return new CSVPrinter(out, this);
}
/**
- * Prints to the specified output.
+ * Prints to the specified {@code File} with given {@code Charset}.
*
*
* See also {@link CSVPrinter}.
*
*
- * @param out
- * the output.
- * @param charset
- * A charset.
+ * @param out the output.
+ * @param charset A charset.
* @return a printer to an output.
- * @throws IOException
- * thrown if the optional header cannot be printed.
+ * @throws IOException thrown if the optional header cannot be printed.
* @since 1.5
*/
- @SuppressWarnings("resource")
public CSVPrinter print(final File out, final Charset charset) throws IOException {
- // The writer will be closed when close() is called.
- return new CSVPrinter(new OutputStreamWriter(new FileOutputStream(out), charset), this);
+ return print(out.toPath(), charset);
+ }
+
+ private void print(final InputStream inputStream, final Appendable out, final boolean newRecord) throws IOException {
+ // InputStream is never null here
+ // There is nothing to escape when quoting is used which is the default.
+ if (!newRecord) {
+ append(getDelimiterString(), out);
+ }
+ final boolean quoteCharacterSet = isQuoteCharacterSet();
+ if (quoteCharacterSet) {
+ append(getQuoteCharacter().charValue(), out); // Explicit unboxing is intentional
+ }
+ // Stream the input to the output without reading or holding the whole value in memory.
+ // AppendableOutputStream cannot "close" an Appendable.
+ try (OutputStream outputStream = new Base64OutputStream(new AppendableOutputStream<>(out))) {
+ IOUtils.copy(inputStream, outputStream);
+ }
+ if (quoteCharacterSet) {
+ append(getQuoteCharacter().charValue(), out); // Explicit unboxing is intentional
+ }
}
/**
- * Prints the {@code value} as the next value on the line to {@code out}. The value will be escaped or encapsulated
- * as needed. Useful when one wants to avoid creating CSVPrinters.
+ * Prints the {@code value} as the next value on the line to {@code out}. The value will be escaped or encapsulated as needed. Useful when one wants to
+ * avoid creating CSVPrinters. Trims the value if {@link #getTrim()} is true.
*
- * @param value
- * value to output.
- * @param out
- * where to print the value.
- * @param newRecord
- * if this a new record.
- * @throws IOException
- * If an I/O error occurs.
+ * @param value value to output.
+ * @param out where to print the value.
+ * @param newRecord if this a new record.
+ * @throws IOException If an I/O error occurs.
* @since 1.4
*/
- public void print(final Object value, final Appendable out, final boolean newRecord) throws IOException {
+ public synchronized void print(final Object value, final Appendable out, final boolean newRecord) throws IOException {
// null values are considered empty
// Only call CharSequence.toString() if you have to, helps GC-free use cases.
CharSequence charSequence;
if (value == null) {
// https://issues.apache.org/jira/browse/CSV-203
if (null == nullString) {
- charSequence = EMPTY;
+ charSequence = Constants.EMPTY;
+ } else if (QuoteMode.ALL == quoteMode) {
+ charSequence = quotedNullString;
} else {
- if (QuoteMode.ALL == quoteMode) {
- charSequence = quotedNullString;
- } else {
- charSequence = nullString;
- }
+ charSequence = nullString;
}
+ } else if (value instanceof CharSequence) {
+ charSequence = (CharSequence) value;
+ } else if (value instanceof Reader) {
+ print((Reader) value, out, newRecord);
+ return;
+ } else if (value instanceof InputStream) {
+ print((InputStream) value, out, newRecord);
+ return;
} else {
- if (value instanceof CharSequence) {
- charSequence = (CharSequence) value;
- } else if (value instanceof Reader) {
- print((Reader) value, out, newRecord);
- return;
- } else {
- charSequence = value.toString();
- }
+ charSequence = value.toString();
}
charSequence = getTrim() ? trim(charSequence) : charSequence;
print(value, charSequence, out, newRecord);
}
- private void print(final Object object, final CharSequence value, final Appendable out, final boolean newRecord)
- throws IOException {
+ private synchronized void print(final Object object, final CharSequence value, final Appendable out, final boolean newRecord) throws IOException {
final int offset = 0;
final int len = value.length();
if (!newRecord) {
- out.append(getDelimiter());
+ out.append(getDelimiterString());
}
if (object == null) {
out.append(value);
} else if (isQuoteCharacterSet()) {
- // the original object is needed so can check for Number
+ // The original object is needed so can check for Number
printWithQuotes(object, value, out, newRecord);
} else if (isEscapeCharacterSet()) {
printWithEscapes(value, out);
@@ -1215,29 +2253,27 @@ private void print(final Object object, final CharSequence value, final Appendab
}
/**
- * Prints to the specified output.
+ * Prints to the specified {@code Path} with given {@code Charset}, returns a {@code CSVPrinter} which the caller MUST close.
*
*
* See also {@link CSVPrinter}.
*
*
- * @param out
- * the output.
- * @param charset
- * A charset.
+ * @param out the output.
+ * @param charset A charset.
* @return a printer to an output.
- * @throws IOException
- * thrown if the optional header cannot be printed.
+ * @throws IOException thrown if the optional header cannot be printed.
* @since 1.5
*/
+ @SuppressWarnings("resource")
public CSVPrinter print(final Path out, final Charset charset) throws IOException {
return print(Files.newBufferedWriter(out, charset));
}
private void print(final Reader reader, final Appendable out, final boolean newRecord) throws IOException {
- // Reader is never null
+ // Reader is never null here
if (!newRecord) {
- out.append(getDelimiter());
+ append(getDelimiterString(), out);
}
if (isQuoteCharacterSet()) {
printWithQuotes(reader, out);
@@ -1248,7 +2284,6 @@ private void print(final Reader reader, final Appendable out, final boolean newR
} else {
IOUtils.copy(reader, out);
}
-
}
/**
@@ -1259,8 +2294,7 @@ private void print(final Reader reader, final Appendable out, final boolean newR
*
*
* @return a printer to {@link System#out}.
- * @throws IOException
- * thrown if the optional header cannot be printed.
+ * @throws IOException thrown if the optional header cannot be printed.
* @since 1.5
*/
public CSVPrinter printer() throws IOException {
@@ -1270,73 +2304,77 @@ public CSVPrinter printer() throws IOException {
/**
* Outputs the trailing delimiter (if set) followed by the record separator (if set).
*
- * @param out
- * where to write
- * @throws IOException
- * If an I/O error occurs
+ * @param appendable where to write
+ * @throws IOException If an I/O error occurs.
* @since 1.4
*/
- public void println(final Appendable out) throws IOException {
+ public synchronized void println(final Appendable appendable) throws IOException {
if (getTrailingDelimiter()) {
- out.append(getDelimiter());
+ append(getDelimiterString(), appendable);
}
if (recordSeparator != null) {
- out.append(recordSeparator);
+ append(recordSeparator, appendable);
}
}
/**
- * Prints the given {@code values} to {@code out} as a single record of delimiter separated values followed by the
- * record separator.
+ * Prints the given {@code values} to {@code out} as a single record of delimiter-separated values followed by the record separator.
*
*
- * The values will be quoted if needed. Quotes and new-line characters will be escaped. This method adds the record
- * separator to the output after printing the record, so there is no need to call {@link #println(Appendable)}.
+ * The values will be quoted if needed. Quotes and new-line characters will be escaped. This method adds the record separator to the output after printing
+ * the record, so there is no need to call {@link #println(Appendable)}.
*
*
- * @param out
- * where to write.
- * @param values
- * values to output.
- * @throws IOException
- * If an I/O error occurs.
+ * @param appendable where to write.
+ * @param values values to output.
+ * @throws IOException If an I/O error occurs.
* @since 1.4
*/
- public void printRecord(final Appendable out, final Object... values) throws IOException {
+ public synchronized void printRecord(final Appendable appendable, final Object... values) throws IOException {
for (int i = 0; i < values.length; i++) {
- print(values[i], out, i == 0);
+ print(values[i], appendable, i == 0);
}
- println(out);
+ println(appendable);
}
/*
- * Note: must only be called if escaping is enabled, otherwise will generate NPE
+ * This method must only be called if escaping is enabled, otherwise can throw exceptions.
*/
- private void printWithEscapes(final CharSequence value, final Appendable out) throws IOException {
+ private void printWithEscapes(final CharSequence charSeq, final Appendable appendable) throws IOException {
int start = 0;
int pos = 0;
- final int len = value.length();
- final int end = len;
-
- final char delim = getDelimiter();
- final char escape = getEscapeCharacter().charValue();
-
+ final int end = charSeq.length();
+ final char[] delimArray = getDelimiterCharArray();
+ final int delimLength = delimArray.length;
+ final char escape = getEscapeChar();
+ final boolean quoteSet = isQuoteCharacterSet();
+ final char quote = quoteSet ? getQuoteCharacter().charValue() : 0;
+ final boolean commentMarkerSet = isCommentMarkerSet();
+ final char commentChar = commentMarkerSet ? commentMarker.charValue() : 0; // Explicit unboxing is intentional
while (pos < end) {
- char c = value.charAt(pos);
- if (c == CR || c == LF || c == delim || c == escape) {
+ char c = charSeq.charAt(pos);
+ final boolean isDelimiterStart = isDelimiter(c, charSeq, pos, delimArray, delimLength);
+ final boolean isCr = c == Constants.CR;
+ final boolean isLf = c == Constants.LF;
+ // A leading comment marker would be read back as a comment, so escape it.
+ final boolean isComment = commentMarkerSet && pos == 0 && c == commentChar;
+ if (isCr || isLf || c == escape || quoteSet && c == quote || isDelimiterStart || isComment) {
// write out segment up until this char
if (pos > start) {
- out.append(value, start, pos);
+ appendable.append(charSeq, start, pos);
}
- if (c == LF) {
+ if (isLf) {
c = 'n';
- } else if (c == CR) {
+ } else if (isCr) {
c = 'r';
}
-
- out.append(escape);
- out.append(c);
-
+ escape(c, appendable);
+ if (isDelimiterStart) {
+ for (int i = 1; i < delimLength; i++) {
+ pos++;
+ escape(charSeq.charAt(pos), appendable);
+ }
+ }
start = pos + 1; // start on the current char after this one
}
pos++;
@@ -1344,62 +2382,84 @@ private void printWithEscapes(final CharSequence value, final Appendable out) th
// write last segment
if (pos > start) {
- out.append(value, start, pos);
+ appendable.append(charSeq, start, pos);
}
}
- private void printWithEscapes(final Reader reader, final Appendable out) throws IOException {
+ /*
+ * This method must only be called if escaping is enabled, otherwise can throw exceptions.
+ */
+ private void printWithEscapes(final Reader reader, final Appendable appendable) throws IOException {
int start = 0;
int pos = 0;
-
- final char delim = getDelimiter();
- final char escape = getEscapeCharacter().charValue();
+ @SuppressWarnings("resource") // Temp reader on input reader.
+ final ExtendedBufferedReader bufferedReader = new ExtendedBufferedReader(reader);
+ final char[] delimArray = getDelimiterCharArray();
+ final int delimLength = delimArray.length;
+ final char escape = getEscapeChar();
+ final boolean quoteSet = isQuoteCharacterSet();
+ final char quote = quoteSet ? getQuoteCharacter().charValue() : 0;
+ final boolean commentMarkerSet = isCommentMarkerSet();
+ final char commentChar = commentMarkerSet ? commentMarker.charValue() : 0; // Explicit unboxing is intentional
final StringBuilder builder = new StringBuilder(IOUtils.DEFAULT_BUFFER_SIZE);
-
int c;
- while (-1 != (c = reader.read())) {
+ boolean firstChar = true;
+ final char[] lookAheadBuffer = new char[delimLength - 1];
+ while (EOF != (c = bufferedReader.read())) {
builder.append((char) c);
- if (c == CR || c == LF || c == delim || c == escape) {
+ Arrays.fill(lookAheadBuffer, (char) 0);
+ bufferedReader.peek(lookAheadBuffer);
+ final String test = builder.toString() + new String(lookAheadBuffer);
+ final boolean isDelimiterStart = isDelimiter((char) c, test, pos, delimArray, delimLength);
+ final boolean isCr = c == Constants.CR;
+ final boolean isLf = c == Constants.LF;
+ // A leading comment marker would be read back as a comment, so escape it.
+ final boolean isComment = commentMarkerSet && firstChar && c == commentChar;
+ firstChar = false;
+ if (isCr || isLf || c == escape || quoteSet && c == quote || isDelimiterStart || isComment) {
// write out segment up until this char
if (pos > start) {
- out.append(builder.substring(start, pos));
+ append(builder.substring(start, pos), appendable);
builder.setLength(0);
+ pos = -1;
}
- if (c == LF) {
+ if (isLf) {
c = 'n';
- } else if (c == CR) {
+ } else if (isCr) {
c = 'r';
}
-
- out.append(escape);
- out.append((char) c);
-
+ escape((char) c, appendable);
+ if (isDelimiterStart) {
+ for (int i = 1; i < delimLength; i++) {
+ escape((char) bufferedReader.read(), appendable);
+ }
+ }
start = pos + 1; // start on the current char after this one
}
pos++;
}
-
// write last segment
if (pos > start) {
- out.append(builder.substring(start, pos));
+ appendable.append(builder, start, pos);
}
}
/*
- * Note: must only be called if quoting is enabled, otherwise will generate NPE
+ * This method must only be called if quoting is enabled, otherwise will generate NPE.
+ * The original object is needed so can check for Number
*/
- // the original object is needed so can check for Number
- private void printWithQuotes(final Object object, final CharSequence value, final Appendable out,
- final boolean newRecord) throws IOException {
+ private void printWithQuotes(final Object object, final CharSequence charSeq, final Appendable out, final boolean newRecord) throws IOException {
boolean quote = false;
int start = 0;
int pos = 0;
- final int len = value.length();
- final int end = len;
-
- final char delimChar = getDelimiter();
- final char quoteChar = getQuoteCharacter().charValue();
-
+ final int len = charSeq.length();
+ final char[] delim = getDelimiterCharArray();
+ final int delimLength = delim.length;
+ final char quoteChar = getQuoteCharacter().charValue(); // Explicit unboxing is intentional
+ // If escape char not specified, default to the quote char
+ // This avoids having to keep checking whether there is an escape character
+ // at the cost of checking against quote twice
+ final char escapeChar = isEscapeCharacterSet() ? getEscapeChar() : quoteChar;
QuoteMode quoteModePolicy = getQuoteMode();
if (quoteModePolicy == null) {
quoteModePolicy = QuoteMode.MINIMAL;
@@ -1414,11 +2474,11 @@ private void printWithQuotes(final Object object, final CharSequence value, fina
break;
case NONE:
// Use the existing escaping code
- printWithEscapes(value, out);
+ printWithEscapes(charSeq, out);
return;
case MINIMAL:
if (len <= 0) {
- // always quote an empty token that is the first
+ // Always quote an empty token that is the first
// on the line, as it may be the only thing on the
// line. If it were not quoted in that case,
// an empty line has no tokens.
@@ -1426,17 +2486,17 @@ private void printWithQuotes(final Object object, final CharSequence value, fina
quote = true;
}
} else {
- char c = value.charAt(pos);
-
- if (c <= COMMENT) {
+ char c = charSeq.charAt(pos);
+ if (c <= Constants.COMMENT || isCommentMarkerSet() && c == commentMarker.charValue()) {
// Some other chars at the start of a value caused the parser to fail, so for now
// encapsulate if we start in anything less than '#'. We are being conservative
- // by including the default comment char too.
+ // by including the default comment char and any configured comment marker too,
+ // which the parser would otherwise read back as a comment line.
quote = true;
} else {
- while (pos < end) {
- c = value.charAt(pos);
- if (c == LF || c == CR || c == quoteChar || c == delimChar) {
+ while (pos < len) {
+ c = charSeq.charAt(pos);
+ if (c == Constants.LF || c == Constants.CR || c == quoteChar || c == escapeChar || isDelimiter(c, charSeq, pos, delim, delimLength)) {
quote = true;
break;
}
@@ -1444,99 +2504,75 @@ private void printWithQuotes(final Object object, final CharSequence value, fina
}
if (!quote) {
- pos = end - 1;
- c = value.charAt(pos);
+ pos = len - 1;
+ c = charSeq.charAt(pos);
// Some other chars at the end caused the parser to fail, so for now
// encapsulate if we end in anything less than ' '
- if (c <= SP) {
+ if (isTrimChar(c)) {
quote = true;
}
}
}
}
-
if (!quote) {
- // no encapsulation needed - write out the original value
- out.append(value, start, end);
+ // No encapsulation needed - write out the original value
+ out.append(charSeq, start, len);
return;
}
break;
default:
throw new IllegalStateException("Unexpected Quote value: " + quoteModePolicy);
}
-
if (!quote) {
- // no encapsulation needed - write out the original value
- out.append(value, start, end);
+ // No encapsulation needed - write out the original value
+ out.append(charSeq, start, len);
return;
}
-
- // we hit something that needed encapsulation
+ // We hit something that needed encapsulation
out.append(quoteChar);
-
// Pick up where we left off: pos should be positioned on the first character that caused
// the need for encapsulation.
- while (pos < end) {
- final char c = value.charAt(pos);
- if (c == quoteChar) {
+ while (pos < len) {
+ final char c = charSeq.charAt(pos);
+ if (c == quoteChar || c == escapeChar) {
// write out the chunk up until this point
-
- // add 1 to the length to write out the encapsulator also
- out.append(value, start, pos + 1);
- // put the next starting position on the encapsulator so we will
- // write it out again with the next string (effectively doubling it)
- start = pos;
+ out.append(charSeq, start, pos);
+ out.append(escapeChar); // now output the escape
+ start = pos; // and restart with the matched char
}
pos++;
}
-
- // write the last segment
- out.append(value, start, pos);
+ // Write the last segment
+ out.append(charSeq, start, pos);
out.append(quoteChar);
}
/**
- * Always use quotes unless QuoteMode is NONE, so we not have to look ahead.
+ * Always use quotes unless QuoteMode is NONE, so we do not have to look ahead.
*
- * @throws IOException
+ * @param reader What to print
+ * @param appendable Where to print it
+ * @throws IOException If an I/O error occurs
*/
- private void printWithQuotes(final Reader reader, final Appendable out) throws IOException {
-
+ private void printWithQuotes(final Reader reader, final Appendable appendable) throws IOException {
if (getQuoteMode() == QuoteMode.NONE) {
- printWithEscapes(reader, out);
+ printWithEscapes(reader, appendable);
return;
}
-
- int pos = 0;
-
- final char quote = getQuoteCharacter().charValue();
- final StringBuilder builder = new StringBuilder(IOUtils.DEFAULT_BUFFER_SIZE);
-
- out.append(quote);
-
+ final char quote = getQuoteCharacter().charValue(); // Explicit unboxing is intentional
+ final char escape = isEscapeCharacterSet() ? getEscapeChar() : quote;
+ // (1) Append opening quote
+ append(quote, appendable);
+ // (2) Append Reader contents, doubling quotes and escape characters
int c;
- while (-1 != (c = reader.read())) {
- builder.append((char) c);
- if (c == quote) {
- // write out segment up until this char
- if (pos > 0) {
- out.append(builder.substring(0, pos));
- builder.setLength(0);
- pos = -1;
- }
-
- out.append(quote);
- out.append((char) c);
+ while (EOF != (c = reader.read())) {
+ append((char) c, appendable);
+ if (c == quote || c == escape) {
+ append((char) c, appendable);
}
- pos++;
- }
-
- // write last segment
- if (pos > 0) {
- out.append(builder.substring(0, pos));
}
-
- out.append(quote);
+ // (3) Append closing quote
+ append(quote, appendable);
}
@Override
@@ -1544,23 +2580,27 @@ public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Delimiter=<").append(delimiter).append('>');
if (isEscapeCharacterSet()) {
- sb.append(' ');
+ sb.append(Constants.SP);
sb.append("Escape=<").append(escapeCharacter).append('>');
}
if (isQuoteCharacterSet()) {
- sb.append(' ');
+ sb.append(Constants.SP);
sb.append("QuoteChar=<").append(quoteCharacter).append('>');
}
+ if (quoteMode != null) {
+ sb.append(Constants.SP);
+ sb.append("QuoteMode=<").append(quoteMode).append('>');
+ }
if (isCommentMarkerSet()) {
- sb.append(' ');
+ sb.append(Constants.SP);
sb.append("CommentStart=<").append(commentMarker).append('>');
}
if (isNullStringSet()) {
- sb.append(' ');
+ sb.append(Constants.SP);
sb.append("NullString=<").append(nullString).append('>');
}
if (recordSeparator != null) {
- sb.append(' ');
+ sb.append(Constants.SP);
sb.append("RecordSeparator=<").append(recordSeparator).append('>');
}
if (getIgnoreEmptyLines()) {
@@ -1574,665 +2614,633 @@ public String toString() {
}
sb.append(" SkipHeaderRecord:").append(skipHeaderRecord);
if (headerComments != null) {
- sb.append(' ');
+ sb.append(Constants.SP);
sb.append("HeaderComments:").append(Arrays.toString(headerComments));
}
- if (header != null) {
- sb.append(' ');
- sb.append("Header:").append(Arrays.toString(header));
+ if (headers != null) {
+ sb.append(Constants.SP);
+ sb.append("Header:").append(Arrays.toString(headers));
}
return sb.toString();
}
- private String[] toStringArray(final Object[] values) {
- if (values == null) {
- return null;
- }
- final String[] strings = new String[values.length];
- for (int i = 0; i < values.length; i++) {
- final Object value = values[i];
- strings[i] = value == null ? null : value.toString();
- }
- return strings;
+ String trim(final String value) {
+ return getTrim() ? value.trim() : value;
}
- private CharSequence trim(final CharSequence charSequence) {
- if (charSequence instanceof String) {
- return ((String) charSequence).trim();
- }
- final int count = charSequence.length();
- int len = count;
- int pos = 0;
+ boolean useMaxRows() {
+ return getMaxRows() > 0;
+ }
- while (pos < len && charSequence.charAt(pos) <= SP) {
- pos++;
- }
- while (pos < len && charSequence.charAt(len - 1) <= SP) {
- len--;
- }
- return pos > 0 || len < count ? charSequence.subSequence(pos, len) : charSequence;
+ boolean useRow(final long rowNum) {
+ return !useMaxRows() || rowNum <= getMaxRows();
}
/**
- * Verifies the consistency of the parameters and throws an IllegalArgumentException if necessary.
+ * Verifies the validity and consistency of the attributes, and throws an {@link IllegalArgumentException} if necessary.
+ *
+ * Because an instance can be used for both writing and parsing, not all conditions can be tested here. For example, allowMissingColumnNames is only used
+ * for parsing, so it cannot be used here.
+ *
*
- * @throws IllegalArgumentException
+ * @throws IllegalArgumentException Throw when any attribute is invalid or inconsistent with other attributes.
*/
private void validate() throws IllegalArgumentException {
- if (isLineBreak(delimiter)) {
- throw new IllegalArgumentException("The delimiter cannot be a line break");
- }
-
- if (quoteCharacter != null && delimiter == quoteCharacter.charValue()) {
- throw new IllegalArgumentException(
- "The quoteChar character and the delimiter cannot be the same ('" + quoteCharacter + "')");
+ if (quoteCharacter != null && contains(delimiter, quoteCharacter.charValue())) { // Explicit unboxing is intentional
+ throw new IllegalArgumentException("The quoteChar character and the delimiter cannot be the same ('" + quoteCharacter + "')");
}
-
- if (escapeCharacter != null && delimiter == escapeCharacter.charValue()) {
- throw new IllegalArgumentException(
- "The escape character and the delimiter cannot be the same ('" + escapeCharacter + "')");
+ if (escapeCharacter != null && contains(delimiter, escapeCharacter.charValue())) { // Explicit unboxing is intentional
+ throw new IllegalArgumentException("The escape character and the delimiter cannot be the same ('" + escapeCharacter + "')");
}
-
- if (commentMarker != null && delimiter == commentMarker.charValue()) {
- throw new IllegalArgumentException(
- "The comment start character and the delimiter cannot be the same ('" + commentMarker + "')");
+ if (commentMarker != null && contains(delimiter, commentMarker.charValue())) { // Explicit unboxing is intentional
+ throw new IllegalArgumentException("The comment start character and the delimiter cannot be the same ('" + commentMarker + "')");
}
-
if (quoteCharacter != null && quoteCharacter.equals(commentMarker)) {
- throw new IllegalArgumentException(
- "The comment start character and the quoteChar cannot be the same ('" + commentMarker + "')");
+ throw new IllegalArgumentException("The comment start character and the quoteChar cannot be the same ('" + commentMarker + "')");
}
-
if (escapeCharacter != null && escapeCharacter.equals(commentMarker)) {
- throw new IllegalArgumentException(
- "The comment start and the escape character cannot be the same ('" + commentMarker + "')");
+ throw new IllegalArgumentException("The comment start and the escape character cannot be the same ('" + commentMarker + "')");
}
-
if (escapeCharacter == null && quoteMode == QuoteMode.NONE) {
- throw new IllegalArgumentException("No quotes mode set but no escape character is set");
- }
-
- // validate header
- if (header != null) {
- final Set dupCheck = new HashSet<>();
- for (final String hdr : header) {
- if (!dupCheck.add(hdr)) {
- throw new IllegalArgumentException(
- "The header contains a duplicate entry: '" + hdr + "' in " + Arrays.toString(header));
+ throw new IllegalArgumentException("Quote mode set to NONE but no escape character is set");
+ }
+ // Validate headers
+ if (headers != null && duplicateHeaderMode != DuplicateHeaderMode.ALLOW_ALL) {
+ final Set dupCheckSet = new HashSet<>(headers.length);
+ final boolean emptyDuplicatesAllowed = duplicateHeaderMode == DuplicateHeaderMode.ALLOW_EMPTY;
+ for (final String header : headers) {
+ final boolean blank = isBlank(header);
+ // Sanitize all empty headers to the empty string "" when checking duplicates
+ final boolean containsHeader = !dupCheckSet.add(blank ? "" : header);
+ if (containsHeader && !(blank && emptyDuplicatesAllowed)) {
+ throw new IllegalArgumentException(String.format(
+ "The header contains a duplicate name: \"%s\" in %s. If this is valid then use CSVFormat.Builder.setDuplicateHeaderMode().", header,
+ Arrays.toString(headers)));
}
}
}
}
/**
- * Returns a new {@code CSVFormat} with the missing column names behavior of the format set to {@code true}
+ * Builds a new {@code CSVFormat} that allows duplicate header names.
+ *
+ * @return a new {@code CSVFormat} that allows duplicate header names
+ * @since 1.7
+ * @deprecated Use {@link Builder#setAllowDuplicateHeaderNames(boolean) Builder#setAllowDuplicateHeaderNames(true)}
+ */
+ @Deprecated
+ public CSVFormat withAllowDuplicateHeaderNames() {
+ return builder().setDuplicateHeaderMode(DuplicateHeaderMode.ALLOW_ALL).get();
+ }
+
+ /**
+ * Builds a new {@code CSVFormat} with duplicate header names behavior set to the given value.
+ *
+ * @param allowDuplicateHeaderNames the duplicate header names behavior, true to allow, false to disallow.
+ * @return a new {@code CSVFormat} with duplicate header names behavior set to the given value.
+ * @since 1.7
+ * @deprecated Use {@link Builder#setAllowDuplicateHeaderNames(boolean)}
+ */
+ @Deprecated
+ public CSVFormat withAllowDuplicateHeaderNames(final boolean allowDuplicateHeaderNames) {
+ final DuplicateHeaderMode mode = allowDuplicateHeaderNames ? DuplicateHeaderMode.ALLOW_ALL : DuplicateHeaderMode.ALLOW_EMPTY;
+ return builder().setDuplicateHeaderMode(mode).get();
+ }
+
+ /**
+ * Builds a new {@code CSVFormat} with the missing column names behavior of the format set to {@code true}.
*
* @return A new CSVFormat that is equal to this but with the specified missing column names behavior.
- * @see #withAllowMissingColumnNames(boolean)
+ * @see Builder#setAllowMissingColumnNames(boolean)
* @since 1.1
+ * @deprecated Use {@link Builder#setAllowMissingColumnNames(boolean) Builder#setAllowMissingColumnNames(true)}
*/
+ @Deprecated
public CSVFormat withAllowMissingColumnNames() {
- return this.withAllowMissingColumnNames(true);
+ return builder().setAllowMissingColumnNames(true).get();
}
/**
- * Returns a new {@code CSVFormat} with the missing column names behavior of the format set to the given value.
+ * Builds a new {@code CSVFormat} with the missing column names behavior of the format set to the given value.
*
- * @param allowMissingColumnNames
- * the missing column names behavior, {@code true} to allow missing column names in the header line,
- * {@code false} to cause an {@link IllegalArgumentException} to be thrown.
+ * @param allowMissingColumnNames the missing column names behavior, {@code true} to allow missing column names in the header line, {@code false} to cause
+ * an {@link IllegalArgumentException} to be thrown.
* @return A new CSVFormat that is equal to this but with the specified missing column names behavior.
+ * @deprecated Use {@link Builder#setAllowMissingColumnNames(boolean)}
*/
+ @Deprecated
public CSVFormat withAllowMissingColumnNames(final boolean allowMissingColumnNames) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setAllowMissingColumnNames(allowMissingColumnNames).get();
}
/**
- * Returns a new {@code CSVFormat} with whether to flush on close.
- *
- * @param autoFlush
- * whether to flush on close.
+ * Builds a new {@code CSVFormat} with whether to flush on close.
*
+ * @param autoFlush whether to flush on close.
* @return A new CSVFormat that is equal to this but with the specified autoFlush setting.
* @since 1.6
+ * @deprecated Use {@link Builder#setAutoFlush(boolean)}
*/
+ @Deprecated
public CSVFormat withAutoFlush(final boolean autoFlush) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setAutoFlush(autoFlush).get();
}
/**
- * Returns a new {@code CSVFormat} with the comment start marker of the format set to the specified character.
+ * Builds a new {@code CSVFormat} with the comment start marker of the format set to the specified character.
*
* Note that the comment start character is only recognized at the start of a line.
*
- * @param commentMarker
- * the comment start marker
+ * @param commentMarker the comment start marker
* @return A new CSVFormat that is equal to this one but with the specified character as the comment start marker
- * @throws IllegalArgumentException
- * thrown if the specified character is a line break
+ * @throws IllegalArgumentException thrown if the specified character is a line break
+ * @deprecated Use {@link Builder#setCommentMarker(char)}
*/
+ @Deprecated
public CSVFormat withCommentMarker(final char commentMarker) {
- return withCommentMarker(Character.valueOf(commentMarker));
+ return builder().setCommentMarker(commentMarker).get();
}
/**
- * Returns a new {@code CSVFormat} with the comment start marker of the format set to the specified character.
+ * Builds a new {@code CSVFormat} with the comment start marker of the format set to the specified character.
*
* Note that the comment start character is only recognized at the start of a line.
*
- * @param commentMarker
- * the comment start marker, use {@code null} to disable
+ * @param commentMarker the comment start marker, use {@code null} to disable
* @return A new CSVFormat that is equal to this one but with the specified character as the comment start marker
- * @throws IllegalArgumentException
- * thrown if the specified character is a line break
+ * @throws IllegalArgumentException thrown if the specified character is a line break
+ * @deprecated Use {@link Builder#setCommentMarker(Character)}
*/
+ @Deprecated
public CSVFormat withCommentMarker(final Character commentMarker) {
- if (isLineBreak(commentMarker)) {
- throw new IllegalArgumentException("The comment start marker character cannot be a line break");
- }
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setCommentMarker(commentMarker).get();
}
/**
- * Returns a new {@code CSVFormat} with the delimiter of the format set to the specified character.
+ * Builds a new {@code CSVFormat} with the delimiter of the format set to the specified character.
*
- * @param delimiter
- * the delimiter character
- * @return A new CSVFormat that is equal to this with the specified character as delimiter
- * @throws IllegalArgumentException
- * thrown if the specified character is a line break
+ * @param delimiter the delimiter character
+ * @return A new CSVFormat that is equal to this with the specified character as a delimiter
+ * @throws IllegalArgumentException thrown if the specified character is a line break
+ * @deprecated Use {@link Builder#setDelimiter(char)}
*/
+ @Deprecated
public CSVFormat withDelimiter(final char delimiter) {
- if (isLineBreak(delimiter)) {
- throw new IllegalArgumentException("The delimiter cannot be a line break");
- }
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setDelimiter(delimiter).get();
}
/**
- * Returns a new {@code CSVFormat} with the escape character of the format set to the specified character.
+ * Builds a new {@code CSVFormat} with the escape character of the format set to the specified character.
*
- * @param escape
- * the escape character
- * @return A new CSVFormat that is equal to his but with the specified character as the escape character
- * @throws IllegalArgumentException
- * thrown if the specified character is a line break
+ * @param escape the escape character
+ * @return A new CSVFormat that is equal to this but with the specified character as the escape character
+ * @throws IllegalArgumentException thrown if the specified character is a line break
+ * @deprecated Use {@link Builder#setEscape(char)}
*/
+ @Deprecated
public CSVFormat withEscape(final char escape) {
- return withEscape(Character.valueOf(escape));
+ return builder().setEscape(escape).get();
}
/**
- * Returns a new {@code CSVFormat} with the escape character of the format set to the specified character.
+ * Builds a new {@code CSVFormat} with the escape character of the format set to the specified character.
*
- * @param escape
- * the escape character, use {@code null} to disable
+ * @param escape the escape character, use {@code null} to disable
* @return A new CSVFormat that is equal to this but with the specified character as the escape character
- * @throws IllegalArgumentException
- * thrown if the specified character is a line break
+ * @throws IllegalArgumentException thrown if the specified character is a line break
+ * @deprecated Use {@link Builder#setEscape(Character)}
*/
+ @Deprecated
public CSVFormat withEscape(final Character escape) {
- if (isLineBreak(escape)) {
- throw new IllegalArgumentException("The escape character cannot be a line break");
- }
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escape, ignoreSurroundingSpaces,
- ignoreEmptyLines, recordSeparator, nullString, headerComments, header, skipHeaderRecord,
- allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setEscape(escape).get();
}
+ // @formatter:off
/**
- * Returns a new {@code CSVFormat} using the first record as header.
+ * Builds a new {@code CSVFormat} using the first record as header.
*
*
Any previously set headers are reset to empty.
+ * The resulting format will have {@code skipHeaderRecord = true}.
+ *
* @return A new CSVFormat that is equal to this but using the first record as header.
- * @see #withSkipHeaderRecord(boolean)
- * @see #withHeader(String...)
+ * @see Builder#setSkipHeaderRecord(boolean)
+ * @see Builder#setHeader(String...)
* @since 1.3
+ * @deprecated Use {@link Builder#setHeader(String...) Builder#setHeader()}.{@link Builder#setSkipHeaderRecord(boolean) setSkipHeaderRecord(true)}.
*/
+ // @formatter:on
+ @Deprecated
public CSVFormat withFirstRecordAsHeader() {
- return withHeader().withSkipHeaderRecord();
+ // @formatter:off
+ return builder()
+ .setHeader()
+ .setSkipHeaderRecord(true)
+ .get();
+ // @formatter:on
}
/**
- * Returns a new {@code CSVFormat} with the header of the format defined by the enum class.
+ * Builds a new {@code CSVFormat} with the header of the format defined by the enum class.
*
*
* Example:
*
*
*
- * public enum Header {
+ * public enum MyHeader {
* Name, Email, Phone
* }
- *
- * CSVFormat format = aformat.withHeader(Header.class);
+ * ...
+ * CSVFormat format = aFormat.builder().setHeader(MyHeader.class).get();
*
*
* The header is also used by the {@link CSVPrinter}.
*
*
- * @param headerEnum
- * the enum defining the header, {@code null} if disabled, empty if parsed automatically, user specified
- * otherwise.
- *
+ * @param headerEnum the enum defining the header, {@code null} if disabled, empty if parsed automatically, user specified otherwise.
* @return A new CSVFormat that is equal to this but with the specified header
- * @see #withHeader(String...)
- * @see #withSkipHeaderRecord(boolean)
+ * @see Builder#setHeader(String...)
+ * @see Builder#setSkipHeaderRecord(boolean)
* @since 1.3
+ * @deprecated Use {@link Builder#setHeader(Class)}
*/
+ @Deprecated
public CSVFormat withHeader(final Class extends Enum>> headerEnum) {
- String[] header = null;
- if (headerEnum != null) {
- final Enum>[] enumValues = headerEnum.getEnumConstants();
- header = new String[enumValues.length];
- for (int i = 0; i < enumValues.length; i++) {
- header[i] = enumValues[i].name();
- }
- }
- return withHeader(header);
+ return builder().setHeader(headerEnum).get();
}
/**
- * Returns a new {@code CSVFormat} with the header of the format set from the result set metadata. The header can
- * either be parsed automatically from the input file with:
+ * Builds a new {@code CSVFormat} with the header of the format set from the result set metadata. The header can either be parsed automatically from the
+ * input file with:
*
*
- * CSVFormat format = aformat.withHeader();
+ * CSVFormat format = aFormat.builder().setHeader().get();
*
*
* or specified manually with:
*
*
- * CSVFormat format = aformat.withHeader(resultSet);
+ * CSVFormat format = aFormat.builder().setHeader(resultSet).get();
*
*
* The header is also used by the {@link CSVPrinter}.
*
*
- * @param resultSet
- * the resultSet for the header, {@code null} if disabled, empty if parsed automatically, user specified
- * otherwise.
- *
+ * @param resultSet the resultSet for the header, {@code null} if disabled, empty if parsed automatically, user-specified otherwise.
* @return A new CSVFormat that is equal to this but with the specified header
- * @throws SQLException
- * SQLException if a database access error occurs or this method is called on a closed result set.
+ * @throws SQLException SQLException if a database access error occurs or this method is called on a closed result set.
* @since 1.1
+ * @deprecated Use {@link Builder#setHeader(ResultSet)}
*/
+ @Deprecated
public CSVFormat withHeader(final ResultSet resultSet) throws SQLException {
- return withHeader(resultSet != null ? resultSet.getMetaData() : null);
+ return builder().setHeader(resultSet).get();
}
/**
- * Returns a new {@code CSVFormat} with the header of the format set from the result set metadata. The header can
- * either be parsed automatically from the input file with:
+ * Builds a new {@code CSVFormat} with the header of the format set from the result set metadata. The header can either be parsed automatically from the
+ * input file with:
*
*
- * CSVFormat format = aformat.withHeader();
+ * CSVFormat format = aFormat.builder().setHeader().get()
*
*
* or specified manually with:
*
*
- * CSVFormat format = aformat.withHeader(metaData);
+ * CSVFormat format = aFormat.builder().setHeader(resultSetMetaData).get()
*
*
* The header is also used by the {@link CSVPrinter}.
*
*
- * @param metaData
- * the metaData for the header, {@code null} if disabled, empty if parsed automatically, user specified
- * otherwise.
- *
+ * @param resultSetMetaData the metaData for the header, {@code null} if disabled, empty if parsed automatically, user specified otherwise.
* @return A new CSVFormat that is equal to this but with the specified header
- * @throws SQLException
- * SQLException if a database access error occurs or this method is called on a closed result set.
+ * @throws SQLException SQLException if a database access error occurs or this method is called on a closed result set.
* @since 1.1
+ * @deprecated Use {@link Builder#setHeader(ResultSetMetaData)}
*/
- public CSVFormat withHeader(final ResultSetMetaData metaData) throws SQLException {
- String[] labels = null;
- if (metaData != null) {
- final int columnCount = metaData.getColumnCount();
- labels = new String[columnCount];
- for (int i = 0; i < columnCount; i++) {
- labels[i] = metaData.getColumnLabel(i + 1);
- }
- }
- return withHeader(labels);
+ @Deprecated
+ public CSVFormat withHeader(final ResultSetMetaData resultSetMetaData) throws SQLException {
+ return builder().setHeader(resultSetMetaData).get();
}
/**
- * Returns a new {@code CSVFormat} with the header of the format set to the given values. The header can either be
- * parsed automatically from the input file with:
+ * Builds a new {@code CSVFormat} with the header of the format set to the given values. The header can either be parsed automatically from the input file
+ * with:
*
*
- * CSVFormat format = aformat.withHeader();
+ * CSVFormat format = aFormat.builder().setHeader().get();
*
*
* or specified manually with:
*
- *
- * CSVFormat format = aformat.withHeader("name", "email", "phone");
- *
* The header is also used by the {@link CSVPrinter}.
*
*
- * @param header
- * the header, {@code null} if disabled, empty if parsed automatically, user specified otherwise.
- *
+ * @param header the header, {@code null} if disabled, empty if parsed automatically, user-specified otherwise.
* @return A new CSVFormat that is equal to this but with the specified header
- * @see #withSkipHeaderRecord(boolean)
+ * @see Builder#setSkipHeaderRecord(boolean)
+ * @deprecated Use {@link Builder#setHeader(String...)}
*/
+ @Deprecated
public CSVFormat withHeader(final String... header) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setHeader(header).get();
}
/**
- * Returns a new {@code CSVFormat} with the header comments of the format set to the given values. The comments will
- * be printed first, before the headers. This setting is ignored by the parser.
- *
- *
- * CSVFormat format = aformat.withHeaderComments("Generated by Apache Commons CSV 1.1.", new Date());
- *
+ * Builds a new {@code CSVFormat} with the header comments of the format set to the given values. The comments will be printed first, before the headers.
+ * This setting is ignored by the parser.
*
- * @param headerComments
- * the headerComments which will be printed by the Printer before the actual CSV data.
+ *
{@code
+ * CSVFormat format = aFormat.builder().setHeaderComments("Generated by Apache Commons CSV.", Instant.now()).get();
+ * }
*
+ * @param headerComments the headerComments which will be printed by the Printer before the actual CSV data.
* @return A new CSVFormat that is equal to this but with the specified header
- * @see #withSkipHeaderRecord(boolean)
+ * @see Builder#setSkipHeaderRecord(boolean)
* @since 1.1
+ * @deprecated Use {@link Builder#setHeaderComments(Object...)}
*/
+ @Deprecated
public CSVFormat withHeaderComments(final Object... headerComments) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setHeaderComments(headerComments).get();
}
/**
- * Returns a new {@code CSVFormat} with the empty line skipping behavior of the format set to {@code true}.
+ * Builds a new {@code CSVFormat} with the empty line skipping behavior of the format set to {@code true}.
*
* @return A new CSVFormat that is equal to this but with the specified empty line skipping behavior.
- * @since {@link #withIgnoreEmptyLines(boolean)}
+ * @see Builder#setIgnoreEmptyLines(boolean)
* @since 1.1
+ * @deprecated Use {@link Builder#setIgnoreEmptyLines(boolean) Builder#setIgnoreEmptyLines(true)}
*/
+ @Deprecated
public CSVFormat withIgnoreEmptyLines() {
- return this.withIgnoreEmptyLines(true);
+ return builder().setIgnoreEmptyLines(true).get();
}
/**
- * Returns a new {@code CSVFormat} with the empty line skipping behavior of the format set to the given value.
+ * Builds a new {@code CSVFormat} with the empty line skipping behavior of the format set to the given value.
*
- * @param ignoreEmptyLines
- * the empty line skipping behavior, {@code true} to ignore the empty lines between the records,
- * {@code false} to translate empty lines to empty records.
+ * @param ignoreEmptyLines the empty line skipping behavior, {@code true} to ignore the empty lines between the records, {@code false} to translate empty
+ * lines to empty records.
* @return A new CSVFormat that is equal to this but with the specified empty line skipping behavior.
+ * @deprecated Use {@link Builder#setIgnoreEmptyLines(boolean)}
*/
+ @Deprecated
public CSVFormat withIgnoreEmptyLines(final boolean ignoreEmptyLines) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setIgnoreEmptyLines(ignoreEmptyLines).get();
}
/**
- * Returns a new {@code CSVFormat} with the header ignore case behavior set to {@code true}.
+ * Builds a new {@code CSVFormat} with the header ignore case behavior set to {@code true}.
*
- * @return A new CSVFormat that will ignore case header name.
- * @see #withIgnoreHeaderCase(boolean)
+ * @return A new CSVFormat that will ignore the new case header name behavior.
+ * @see Builder#setIgnoreHeaderCase(boolean)
* @since 1.3
+ * @deprecated Use {@link Builder#setIgnoreHeaderCase(boolean) Builder#setIgnoreHeaderCase(true)}
*/
+ @Deprecated
public CSVFormat withIgnoreHeaderCase() {
- return this.withIgnoreHeaderCase(true);
+ return builder().setIgnoreHeaderCase(true).get();
}
/**
- * Returns a new {@code CSVFormat} with whether header names should be accessed ignoring case.
+ * Builds a new {@code CSVFormat} with whether header names should be accessed ignoring case.
*
- * @param ignoreHeaderCase
- * the case mapping behavior, {@code true} to access name/values, {@code false} to leave the mapping as
- * is.
+ * @param ignoreHeaderCase the case mapping behavior, {@code true} to access name/values, {@code false} to leave the mapping as is.
* @return A new CSVFormat that will ignore case header name if specified as {@code true}
* @since 1.3
+ * @deprecated Use {@link Builder#setIgnoreHeaderCase(boolean)}
*/
+ @Deprecated
public CSVFormat withIgnoreHeaderCase(final boolean ignoreHeaderCase) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setIgnoreHeaderCase(ignoreHeaderCase).get();
}
/**
- * Returns a new {@code CSVFormat} with the trimming behavior of the format set to {@code true}.
+ * Builds a new {@code CSVFormat} with the parser trimming behavior of the format set to {@code true}.
*
- * @return A new CSVFormat that is equal to this but with the specified trimming behavior.
- * @see #withIgnoreSurroundingSpaces(boolean)
+ * @return A new CSVFormat that is equal to this but with the specified parser trimming behavior.
+ * @see Builder#setIgnoreSurroundingSpaces(boolean)
* @since 1.1
+ * @deprecated Use {@link Builder#setIgnoreSurroundingSpaces(boolean) Builder#setIgnoreSurroundingSpaces(true)}
*/
+ @Deprecated
public CSVFormat withIgnoreSurroundingSpaces() {
- return this.withIgnoreSurroundingSpaces(true);
+ return builder().setIgnoreSurroundingSpaces(true).get();
}
/**
- * Returns a new {@code CSVFormat} with the trimming behavior of the format set to the given value.
+ * Builds a new {@code CSVFormat} with the parser trimming behavior of the format set to the given value.
*
- * @param ignoreSurroundingSpaces
- * the trimming behavior, {@code true} to remove the surrounding spaces, {@code false} to leave the
- * spaces as is.
+ * @param ignoreSurroundingSpaces the parser trimming behavior, {@code true} to remove the surrounding spaces, {@code false} to leave the spaces as is.
* @return A new CSVFormat that is equal to this but with the specified trimming behavior.
+ * @deprecated Use {@link Builder#setIgnoreSurroundingSpaces(boolean)}
*/
+ @Deprecated
public CSVFormat withIgnoreSurroundingSpaces(final boolean ignoreSurroundingSpaces) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setIgnoreSurroundingSpaces(ignoreSurroundingSpaces).get();
}
/**
- * Returns a new {@code CSVFormat} with conversions to and from null for strings on input and output.
+ * Builds a new {@code CSVFormat} with conversions to and from null for strings on input and output.
*
- *
Reading: Converts strings equal to the given {@code nullString} to {@code null} when reading
- * records.
+ *
Reading: Converts strings equal to the given {@code nullString} to {@code null} when reading records.
*
Writing: Writes {@code null} as the given {@code nullString} when writing records.
*
*
- * @param nullString
- * the String to convert to and from {@code null}. No substitution occurs if {@code null}
- *
+ * @param nullString the String to convert to and from {@code null}. No substitution occurs if {@code null}
* @return A new CSVFormat that is equal to this but with the specified null conversion string.
+ * @deprecated Use {@link Builder#setNullString(String)}
*/
+ @Deprecated
public CSVFormat withNullString(final String nullString) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setNullString(nullString).get();
}
/**
- * Returns a new {@code CSVFormat} with the quoteChar of the format set to the specified character.
+ * Builds a new {@code CSVFormat} with the quoteChar of the format set to the specified character.
*
- * @param quoteChar
- * the quoteChar character
+ * @param quoteChar the quote character
* @return A new CSVFormat that is equal to this but with the specified character as quoteChar
- * @throws IllegalArgumentException
- * thrown if the specified character is a line break
+ * @throws IllegalArgumentException thrown if the specified character is a line break
+ * @deprecated Use {@link Builder#setQuote(char)}
*/
+ @Deprecated
public CSVFormat withQuote(final char quoteChar) {
- return withQuote(Character.valueOf(quoteChar));
+ return builder().setQuote(quoteChar).get();
}
/**
- * Returns a new {@code CSVFormat} with the quoteChar of the format set to the specified character.
+ * Builds a new {@code CSVFormat} with the quoteChar of the format set to the specified character.
*
- * @param quoteChar
- * the quoteChar character, use {@code null} to disable
+ * @param quoteChar the quote character, use {@code null} to disable.
* @return A new CSVFormat that is equal to this but with the specified character as quoteChar
- * @throws IllegalArgumentException
- * thrown if the specified character is a line break
+ * @throws IllegalArgumentException thrown if the specified character is a line break
+ * @deprecated Use {@link Builder#setQuote(Character)}
*/
+ @Deprecated
public CSVFormat withQuote(final Character quoteChar) {
- if (isLineBreak(quoteChar)) {
- throw new IllegalArgumentException("The quoteChar cannot be a line break");
- }
- return new CSVFormat(delimiter, quoteChar, quoteMode, commentMarker, escapeCharacter, ignoreSurroundingSpaces,
- ignoreEmptyLines, recordSeparator, nullString, headerComments, header, skipHeaderRecord,
- allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setQuote(quoteChar).get();
}
/**
- * Returns a new {@code CSVFormat} with the output quote policy of the format set to the specified value.
- *
- * @param quoteModePolicy
- * the quote policy to use for output.
+ * Builds a new {@code CSVFormat} with the output quote policy of the format set to the specified value.
*
+ * @param quoteMode the quote policy to use for output.
* @return A new CSVFormat that is equal to this but with the specified quote policy
+ * @deprecated Use {@link Builder#setQuoteMode(QuoteMode)}
*/
- public CSVFormat withQuoteMode(final QuoteMode quoteModePolicy) {
- return new CSVFormat(delimiter, quoteCharacter, quoteModePolicy, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ @Deprecated
+ public CSVFormat withQuoteMode(final QuoteMode quoteMode) {
+ return builder().setQuoteMode(quoteMode).get();
}
/**
- * Returns a new {@code CSVFormat} with the record separator of the format set to the specified character.
+ * Builds a new {@code CSVFormat} with the record separator of the format set to the specified character.
*
*
- * Note: This setting is only used during printing and does not affect parsing. Parsing currently
- * only works for inputs with '\n', '\r' and "\r\n"
+ * Note: This setting is only used during printing and does not affect parsing. Parsing currently only works for inputs with '\n', '\r' and
+ * "\r\n"
*
*
- * @param recordSeparator
- * the record separator to use for output.
- *
+ * @param recordSeparator the record separator to use for output.
* @return A new CSVFormat that is equal to this but with the specified output record separator
+ * @deprecated Use {@link Builder#setRecordSeparator(char)}
*/
+ @Deprecated
public CSVFormat withRecordSeparator(final char recordSeparator) {
- return withRecordSeparator(String.valueOf(recordSeparator));
+ return builder().setRecordSeparator(recordSeparator).get();
}
/**
- * Returns a new {@code CSVFormat} with the record separator of the format set to the specified String.
+ * Builds a new {@code CSVFormat} with the record separator of the format set to the specified String.
*
*
- * Note: This setting is only used during printing and does not affect parsing. Parsing currently
- * only works for inputs with '\n', '\r' and "\r\n"
+ * Note: This setting is only used during printing and does not affect parsing. Parsing currently only works for inputs with '\n', '\r' and
+ * "\r\n"
*
*
- * @param recordSeparator
- * the record separator to use for output.
- *
+ * @param recordSeparator the record separator to use for output.
* @return A new CSVFormat that is equal to this but with the specified output record separator
- * @throws IllegalArgumentException
- * if recordSeparator is none of CR, LF or CRLF
+ * @throws IllegalArgumentException if recordSeparator is none of CR, LF or CRLF
+ * @deprecated Use {@link Builder#setRecordSeparator(String)}
*/
+ @Deprecated
public CSVFormat withRecordSeparator(final String recordSeparator) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setRecordSeparator(recordSeparator).get();
}
/**
- * Returns a new {@code CSVFormat} with skipping the header record set to {@code true}.
+ * Builds a new {@code CSVFormat} with skipping the header record set to {@code true}.
*
* @return A new CSVFormat that is equal to this but with the specified skipHeaderRecord setting.
- * @see #withSkipHeaderRecord(boolean)
- * @see #withHeader(String...)
+ * @see Builder#setSkipHeaderRecord(boolean)
+ * @see Builder#setHeader(String...)
* @since 1.1
+ * @deprecated Use {@link Builder#setSkipHeaderRecord(boolean) Builder#setSkipHeaderRecord(true)}
*/
+ @Deprecated
public CSVFormat withSkipHeaderRecord() {
- return this.withSkipHeaderRecord(true);
+ return builder().setSkipHeaderRecord(true).get();
}
/**
- * Returns a new {@code CSVFormat} with whether to skip the header record.
- *
- * @param skipHeaderRecord
- * whether to skip the header record.
+ * Builds a new {@code CSVFormat} with whether to skip the header record.
*
+ * @param skipHeaderRecord whether to skip the header record.
* @return A new CSVFormat that is equal to this but with the specified skipHeaderRecord setting.
- * @see #withHeader(String...)
+ * @see Builder#setHeader(String...)
+ * @deprecated Use {@link Builder#setSkipHeaderRecord(boolean)}
*/
+ @Deprecated
public CSVFormat withSkipHeaderRecord(final boolean skipHeaderRecord) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setSkipHeaderRecord(skipHeaderRecord).get();
}
/**
- * Returns a new {@code CSVFormat} with the record separator of the format set to the operating system's line
- * separator string, typically CR+LF on Windows and LF on Linux.
+ * Builds a new {@code CSVFormat} with the record separator of the format set to the operating system's line separator string, typically CR+LF on Windows
+ * and LF on Linux.
*
*
- * Note: This setting is only used during printing and does not affect parsing. Parsing currently
- * only works for inputs with '\n', '\r' and "\r\n"
+ * Note: This setting is only used during printing and does not affect parsing. Parsing currently only works for inputs with '\n', '\r' and
+ * "\r\n"
*
*
* @return A new CSVFormat that is equal to this but with the operating system's line separator string.
* @since 1.6
+ * @deprecated Use {@link Builder#setRecordSeparator(String) setRecordSeparator(System.lineSeparator())}
*/
+ @Deprecated
public CSVFormat withSystemRecordSeparator() {
- return withRecordSeparator(System.getProperty("line.separator"));
+ return builder().setRecordSeparator(System.lineSeparator()).get();
}
/**
- * Returns a new {@code CSVFormat} to add a trailing delimiter.
+ * Builds a new {@code CSVFormat} to add a trailing delimiter.
*
* @return A new CSVFormat that is equal to this but with the trailing delimiter setting.
* @since 1.3
+ * @deprecated Use {@link Builder#setTrailingDelimiter(boolean) Builder#setTrailingDelimiter(true)}
*/
+ @Deprecated
public CSVFormat withTrailingDelimiter() {
- return withTrailingDelimiter(true);
+ return builder().setTrailingDelimiter(true).get();
}
/**
- * Returns a new {@code CSVFormat} with whether to add a trailing delimiter.
- *
- * @param trailingDelimiter
- * whether to add a trailing delimiter.
+ * Builds a new {@code CSVFormat} with whether to add a trailing delimiter.
*
+ * @param trailingDelimiter whether to add a trailing delimiter.
* @return A new CSVFormat that is equal to this but with the specified trailing delimiter setting.
* @since 1.3
+ * @deprecated Use {@link Builder#setTrailingDelimiter(boolean)}
*/
+ @Deprecated
public CSVFormat withTrailingDelimiter(final boolean trailingDelimiter) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setTrailingDelimiter(trailingDelimiter).get();
}
/**
- * Returns a new {@code CSVFormat} to trim leading and trailing blanks.
+ * Builds a new {@code CSVFormat} to trim leading and trailing blanks. See {@link #getTrim()} for details of where this is used.
*
* @return A new CSVFormat that is equal to this but with the trim setting on.
* @since 1.3
+ * @deprecated Use {@link Builder#setTrim(boolean) Builder#setTrim(true)}
*/
+ @Deprecated
public CSVFormat withTrim() {
- return withTrim(true);
+ return builder().setTrim(true).get();
}
/**
- * Returns a new {@code CSVFormat} with whether to trim leading and trailing blanks.
- *
- * @param trim
- * whether to trim leading and trailing blanks.
+ * Builds a new {@code CSVFormat} with whether to trim leading and trailing blanks. See {@link #getTrim()} for details of where this is used.
*
+ * @param trim whether to trim leading and trailing blanks.
* @return A new CSVFormat that is equal to this but with the specified trim setting.
* @since 1.3
+ * @deprecated Use {@link Builder#setTrim(boolean)}
*/
+ @Deprecated
public CSVFormat withTrim(final boolean trim) {
- return new CSVFormat(delimiter, quoteCharacter, quoteMode, commentMarker, escapeCharacter,
- ignoreSurroundingSpaces, ignoreEmptyLines, recordSeparator, nullString, headerComments, header,
- skipHeaderRecord, allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter, autoFlush);
+ return builder().setTrim(trim).get();
}
+
}
diff --git a/src/main/java/org/apache/commons/csv/CSVParser.java b/src/main/java/org/apache/commons/csv/CSVParser.java
index ecb4c6a138..141eba732c 100644
--- a/src/main/java/org/apache/commons/csv/CSVParser.java
+++ b/src/main/java/org/apache/commons/csv/CSVParser.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
@@ -21,24 +23,35 @@
import java.io.Closeable;
import java.io.File;
-import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
+import java.io.UncheckedIOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.Spliterator;
+import java.util.Spliterators;
import java.util.TreeMap;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+
+import org.apache.commons.io.Charsets;
+import org.apache.commons.io.build.AbstractStreamBuilder;
+import org.apache.commons.io.function.Uncheck;
/**
* Parses CSV files according to the specified format.
@@ -46,7 +59,7 @@
* Because CSV appears in many different dialects, the parser supports many formats by allowing the
* specification of a {@link CSVFormat}.
*
- * The parser works record wise. It is not possible to go back, once a record has been parsed from the input stream.
+ * The parser works record-wise. It is not possible to go back, once a record has been parsed from the input stream.
*
*
Creating instances
*
@@ -63,7 +76,7 @@
* For those who like fluent APIs, parsers can be created using {@link CSVFormat#parse(java.io.Reader)} as a shortcut:
*
*
- * for(CSVRecord record : CSVFormat.EXCEL.parse(in)) {
+ * for (CSVRecord record : CSVFormat.EXCEL.parse(in)) {
* ...
* }
*
@@ -73,17 +86,17 @@
* To parse a CSV input from a file, you write:
*
*
- *
* This will read the parse the contents of the file using the
- * RFC 4180 format.
+ * RFC 4180 format.
*
*
*
@@ -98,20 +111,20 @@
*
*
*
- * If the predefined formats don't match the format at hands, custom formats can be defined. More information about
- * customising CSVFormats is available in {@link CSVFormat CSVFormat Javadoc}.
+ * If the predefined formats don't match the format at hand, custom formats can be defined. More information about
+ * customizing CSVFormats is available in {@link CSVFormat CSVFormat Javadoc}.
*
*
*
Parsing into memory
*
- * If parsing record wise is not desired, the contents of the input can be read completely into memory.
+ * If parsing record-wise is not desired, the contents of the input can be read completely into memory.
*
*
- *
- * Reader in = new StringReader("a;b\nc;d");
+ *
{@code
+ * Reader in = new StringReader("a;b\nc;d");
* CSVParser parser = new CSVParser(in, CSVFormat.EXCEL);
- * List<CSVRecord> list = parser.getRecords();
- *
+ * List list = parser.getRecords();
+ * }
*
*
* There are two constraints that have to be kept in mind:
@@ -119,40 +132,216 @@
*
*
*
Parsing into memory starts at the current position of the parser. If you have already parsed records from
- * the input, those records will not end up in the in memory representation of your CSV data.
- *
Parsing into memory may consume a lot of system resources depending on the input. For example if you're
+ * the input, those records will not end up in the in-memory representation of your CSV data.
+ *
Parsing into memory may consume a lot of system resources depending on the input. For example, if you're
* parsing a 150MB file of CSV data the contents will be read completely into memory.
*
*
*
Notes
*
- * Internal parser state is completely covered by the format and the reader-state.
+ * The internal parser state is completely covered by the format and the reader state.
*
*
* @see package documentation for more details
*/
public final class CSVParser implements Iterable, Closeable {
+ /**
+ * Builds a new {@link CSVParser}.
+ *
+ * @since 1.13.0
+ */
+ public static class Builder extends AbstractStreamBuilder {
+
+ private CSVFormat format;
+ private long byteOffset = -1;
+ private long characterOffset;
+ private long recordNumber = 1;
+ private boolean trackBytes;
+
+ /**
+ * Constructs a new instance.
+ */
+ protected Builder() {
+ // empty
+ }
+
+ @Override
+ public CSVParser get() throws IOException {
+ return new CSVParser(this);
+ }
+
+ /**
+ * Sets the lexer byte offset when the parser does not start parsing at the beginning of the source.
+ *
+ * By default, the value is {@code -1}, which reuses the character offset for the byte offset.
+ *
+ *
+ * @param byteOffset the lexer byte offset.
+ * @return {@code this} instance.
+ * @see #setCharacterOffset(long)
+ * @since 1.15.0
+ */
+ public Builder setByteOffset(final long byteOffset) {
+ this.byteOffset = byteOffset;
+ return asThis();
+ }
+
+ /**
+ * Sets the lexer character offset when the parser does not start parsing at the beginning of the source.
+ *
+ * @param characterOffset the lexer character offset.
+ * @return {@code this} instance.
+ * @see #setByteOffset(long)
+ */
+ public Builder setCharacterOffset(final long characterOffset) {
+ this.characterOffset = characterOffset;
+ return asThis();
+ }
+
+ /**
+ * Sets the CSV format. A copy of the given format is kept.
+ *
+ * @param format the CSV format, {@code null} resets to {@link CSVFormat#DEFAULT}.
+ * @return {@code this} instance.
+ */
+ public Builder setFormat(final CSVFormat format) {
+ this.format = CSVFormat.copy(format);
+ return asThis();
+ }
+
+ /**
+ * Sets the next record number to assign, defaults to {@code 1}.
+ *
+ * @param recordNumber the next record number to assign.
+ * @return {@code this} instance.
+ */
+ public Builder setRecordNumber(final long recordNumber) {
+ this.recordNumber = recordNumber;
+ return asThis();
+ }
+
+ /**
+ * Sets whether to enable byte tracking for the parser.
+ *
+ * @param trackBytes {@code true} to enable byte tracking; {@code false} to disable it.
+ * @return {@code this} instance.
+ * @since 1.13.0
+ */
+ public Builder setTrackBytes(final boolean trackBytes) {
+ this.trackBytes = trackBytes;
+ return asThis();
+ }
+
+ }
+
+ final class CSVRecordIterator implements Iterator {
+ private CSVRecord current;
+ private long recordCount;
+
+ /**
+ * Gets the next record or null at the end of stream or max rows read.
+ *
+ * @throws IOException on parse error or input read-failure
+ * @throws CSVException on invalid input.
+ * @return the next record, or {@code null} if the end of the stream has been reached.
+ */
+ private CSVRecord getNextRecord() {
+ CSVRecord record = null;
+ if (format.useRow(recordCount + 1)) {
+ record = Uncheck.get(CSVParser.this::nextRecord);
+ if (record != null) {
+ recordCount++;
+ }
+ }
+ return record;
+ }
+
+ @Override
+ public boolean hasNext() {
+ if (isClosed()) {
+ return false;
+ }
+ if (current == null) {
+ current = getNextRecord();
+ }
+ return current != null;
+ }
+
+ @Override
+ public CSVRecord next() {
+ if (isClosed()) {
+ throw new NoSuchElementException("CSVParser has been closed");
+ }
+ CSVRecord next = current;
+ current = null;
+ if (next == null) {
+ // hasNext() wasn't called before
+ next = getNextRecord();
+ if (next == null) {
+ throw new NoSuchElementException("No more CSV records available");
+ }
+ }
+ return next;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ /**
+ * Header information based on name and position.
+ */
+ private static final class Headers {
+
+ /**
+ * Header column positions (0-based)
+ */
+ final Map headerMap;
+
+ /**
+ * Header names in column order
+ */
+ final List headerNames;
+
+ Headers(final Map headerMap, final List headerNames) {
+ this.headerMap = headerMap;
+ this.headerNames = headerNames;
+ }
+ }
+
+ /**
+ * Creates a new builder.
+ *
+ * @return a new builder.
+ * @since 1.13.0
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
/**
* Creates a parser for the given {@link File}.
*
* @param file
* a CSV file. Must not be null.
* @param charset
- * A Charset
+ * The Charset to decode the given file, {@code null} maps to the {@link Charset#defaultCharset() default Charset}.
* @param format
- * the CSVFormat used for CSV parsing. Must not be null.
+ * the CSVFormat used for CSV parsing, {@code null} maps to {@link CSVFormat#DEFAULT}.
* @return a new parser
* @throws IllegalArgumentException
- * If the parameters of the format are inconsistent or if either file or format are null.
+ * If the parameters of the format are inconsistent.
* @throws IOException
* If an I/O error occurs
+ * @throws CSVException Thrown on invalid CSV input data.
+ * @throws NullPointerException if {@code file} is {@code null}.
*/
- @SuppressWarnings("resource")
public static CSVParser parse(final File file, final Charset charset, final CSVFormat format) throws IOException {
- Assertions.notNull(file, "file");
- Assertions.notNull(format, "format");
- return new CSVParser(new InputStreamReader(new FileInputStream(file), charset), format);
+ Objects.requireNonNull(file, "file");
+ return parse(file.toPath(), charset, format);
}
/**
@@ -164,45 +353,45 @@ public static CSVParser parse(final File file, final Charset charset, final CSVF
*
*
* @param inputStream
- * an InputStream containing CSV-formatted input. Must not be null.
+ * an InputStream containing CSV-formatted input, {@code null} maps to {@link CSVFormat#DEFAULT}.
* @param charset
- * a Charset.
+ * The Charset to decode the given file, {@code null} maps to the {@link Charset#defaultCharset() default Charset}.
* @param format
- * the CSVFormat used for CSV parsing. Must not be null.
+ * the CSVFormat used for CSV parsing, {@code null} maps to {@link CSVFormat#DEFAULT}.
* @return a new CSVParser configured with the given reader and format.
* @throws IllegalArgumentException
* If the parameters of the format are inconsistent or if either reader or format are null.
* @throws IOException
* If there is a problem reading the header or skipping the first record
+ * @throws CSVException Thrown on invalid CSV input data.
* @since 1.5
*/
- @SuppressWarnings("resource")
public static CSVParser parse(final InputStream inputStream, final Charset charset, final CSVFormat format)
throws IOException {
- Assertions.notNull(inputStream, "inputStream");
- Assertions.notNull(format, "format");
- return parse(new InputStreamReader(inputStream, charset), format);
+ return parse(new InputStreamReader(inputStream, Charsets.toCharset(charset)), format);
}
/**
- * Creates a parser for the given {@link Path}.
+ * Creates and returns a parser for the given {@link Path}, which the caller MUST close.
*
* @param path
* a CSV file. Must not be null.
* @param charset
- * A Charset
+ * The Charset to decode the given file, {@code null} maps to the {@link Charset#defaultCharset() default Charset}.
* @param format
- * the CSVFormat used for CSV parsing. Must not be null.
+ * the CSVFormat used for CSV parsing, {@code null} maps to {@link CSVFormat#DEFAULT}.
* @return a new parser
* @throws IllegalArgumentException
- * If the parameters of the format are inconsistent or if either file or format are null.
+ * If the parameters of the format are inconsistent.
* @throws IOException
* If an I/O error occurs
+ * @throws CSVException Thrown on invalid CSV input data.
+ * @throws NullPointerException if {@code path} is {@code null}.
* @since 1.5
*/
+ @SuppressWarnings("resource")
public static CSVParser parse(final Path path, final Charset charset, final CSVFormat format) throws IOException {
- Assertions.notNull(path, "path");
- Assertions.notNull(format, "format");
+ Objects.requireNonNull(path, "path");
return parse(Files.newInputStream(path), charset, format);
}
@@ -217,16 +406,17 @@ public static CSVParser parse(final Path path, final Charset charset, final CSVF
* @param reader
* a Reader containing CSV-formatted input. Must not be null.
* @param format
- * the CSVFormat used for CSV parsing. Must not be null.
+ * the CSVFormat used for CSV parsing, {@code null} maps to {@link CSVFormat#DEFAULT}.
* @return a new CSVParser configured with the given reader and format.
* @throws IllegalArgumentException
* If the parameters of the format are inconsistent or if either reader or format are null.
* @throws IOException
* If there is a problem reading the header or skipping the first record
+ * @throws CSVException Thrown on invalid CSV input data.
* @since 1.5
*/
public static CSVParser parse(final Reader reader, final CSVFormat format) throws IOException {
- return new CSVParser(reader, format);
+ return builder().setReader(reader).setFormat(format).get();
}
/**
@@ -235,22 +425,22 @@ public static CSVParser parse(final Reader reader, final CSVFormat format) throw
* @param string
* a CSV string. Must not be null.
* @param format
- * the CSVFormat used for CSV parsing. Must not be null.
+ * the CSVFormat used for CSV parsing, {@code null} maps to {@link CSVFormat#DEFAULT}.
* @return a new parser
* @throws IllegalArgumentException
- * If the parameters of the format are inconsistent or if either string or format are null.
+ * If the parameters of the format are inconsistent.
* @throws IOException
* If an I/O error occurs
+ * @throws CSVException Thrown on invalid CSV input data.
+ * @throws NullPointerException if {@code string} is {@code null}.
*/
public static CSVParser parse(final String string, final CSVFormat format) throws IOException {
- Assertions.notNull(string, "string");
- Assertions.notNull(format, "format");
-
- return new CSVParser(new StringReader(string), format);
+ Objects.requireNonNull(string, "string");
+ return parse(new StringReader(string), format);
}
/**
- * Creates a parser for the given URL.
+ * Creates and returns a parser for the given URL, which the caller MUST close.
*
*
* If you do not read all records from the given {@code url}, you should call {@link #close()} on the parser, unless
@@ -260,29 +450,30 @@ public static CSVParser parse(final String string, final CSVFormat format) throw
* @param url
* a URL. Must not be null.
* @param charset
- * the charset for the resource. Must not be null.
+ * the charset for the resource, {@code null} maps to the {@link Charset#defaultCharset() default Charset}.
* @param format
- * the CSVFormat used for CSV parsing. Must not be null.
+ * the CSVFormat used for CSV parsing, {@code null} maps to {@link CSVFormat#DEFAULT}.
* @return a new parser
* @throws IllegalArgumentException
- * If the parameters of the format are inconsistent or if either url, charset or format are null.
+ * If the parameters of the format are inconsistent.
* @throws IOException
* If an I/O error occurs
+ * @throws CSVException Thrown on invalid CSV input data.
+ * @throws NullPointerException if {@code url} is {@code null}.
*/
+ @SuppressWarnings("resource")
public static CSVParser parse(final URL url, final Charset charset, final CSVFormat format) throws IOException {
- Assertions.notNull(url, "url");
- Assertions.notNull(charset, "charset");
- Assertions.notNull(format, "format");
-
- return new CSVParser(new InputStreamReader(url.openStream(), charset), format);
+ Objects.requireNonNull(url, "url");
+ return parse(url.openStream(), charset, format);
}
- // the following objects are shared to reduce garbage
+ private String headerComment;
+
+ private String trailerComment;
private final CSVFormat format;
- /** A mapping of column names to column indices */
- private final Map headerMap;
+ private final Headers headers;
private final Lexer lexer;
@@ -296,6 +487,12 @@ public static CSVParser parse(final URL url, final Charset charset, final CSVFor
*/
private long recordNumber;
+ /**
+ * Lexer offset when the parser does not start parsing at the beginning of the source. Usually used in combination
+ * with {@link #recordNumber}.
+ */
+ private final long byteOffset;
+
/**
* Lexer offset when the parser does not start parsing at the beginning of the source. Usually used in combination
* with {@link #recordNumber}.
@@ -305,7 +502,24 @@ public static CSVParser parse(final URL url, final Charset charset, final CSVFor
private final Token reusableToken = new Token();
/**
- * Customized CSV parser using the given {@link CSVFormat}
+ * Constructs a new instance from a builder.
+ *
+ * @param builder The source builder.
+ * @throws IOException if an I/O error occurs.
+ */
+ @SuppressWarnings("resource") // Lexer manages ExtendedBufferedReader.
+ private CSVParser(final Builder builder) throws IOException {
+ this.format = (builder.format != null ? builder.format : CSVFormat.DEFAULT).copy();
+ this.lexer = new Lexer(format, new ExtendedBufferedReader(builder.getReader(), builder.getCharset(), builder.trackBytes));
+ this.csvRecordIterator = new CSVRecordIterator();
+ this.headers = createHeaders();
+ this.byteOffset = builder.byteOffset != -1 ? builder.byteOffset : builder.characterOffset;
+ this.characterOffset = builder.characterOffset;
+ this.recordNumber = builder.recordNumber - 1;
+ }
+
+ /**
+ * Constructs a new instance using the given {@link CSVFormat}.
*
*
* If you do not read all records from the given {@code reader}, you should call {@link #close()} on the parser,
@@ -320,13 +534,16 @@ public static CSVParser parse(final URL url, final Charset charset, final CSVFor
* If the parameters of the format are inconsistent or if either reader or format are null.
* @throws IOException
* If there is a problem reading the header or skipping the first record
+ * @throws CSVException Thrown on invalid CSV input data.
+ * @deprecated Will be removed in the next major version, use {@link Builder#get()}.
*/
+ @Deprecated
public CSVParser(final Reader reader, final CSVFormat format) throws IOException {
this(reader, format, 0, 1);
}
/**
- * Customized CSV parser using the given {@link CSVFormat}
+ * Constructs a new instance using the given {@link CSVFormat}.
*
*
* If you do not read all records from the given {@code reader}, you should call {@link #close()} on the parser,
@@ -340,35 +557,35 @@ public CSVParser(final Reader reader, final CSVFormat format) throws IOException
* @param characterOffset
* Lexer offset when the parser does not start parsing at the beginning of the source.
* @param recordNumber
- * The next record number to assign
+ * The next record number to assign.
* @throws IllegalArgumentException
- * If the parameters of the format are inconsistent or if either reader or format are null.
+ * If the parameters of the format are inconsistent or if either the reader or format is null.
* @throws IOException
- * If there is a problem reading the header or skipping the first record
+ * if there is a problem reading the header or skipping the first record
+ * @throws CSVException on invalid input.
* @since 1.1
+ * @deprecated Will be removed in the next major version, use {@link Builder#get()}.
*/
- @SuppressWarnings("resource")
- public CSVParser(final Reader reader, final CSVFormat format, final long characterOffset, final long recordNumber)
- throws IOException {
- Assertions.notNull(reader, "reader");
- Assertions.notNull(format, "format");
-
- this.format = format;
- this.lexer = new Lexer(format, new ExtendedBufferedReader(reader));
- this.csvRecordIterator = new CSVRecordIterator();
- this.headerMap = this.initializeHeader();
- this.characterOffset = characterOffset;
- this.recordNumber = recordNumber - 1;
+ @Deprecated
+ public CSVParser(final Reader reader, final CSVFormat format, final long characterOffset, final long recordNumber) throws IOException {
+ // @formatter:off
+ this(builder()
+ .setReader(reader)
+ .setFormat(Objects.requireNonNull(format, "format")) // requireNonNull for full compatibility
+ .setCharacterOffset(characterOffset)
+ .setRecordNumber(recordNumber)
+ .setCharset((Charset) null).setTrackBytes(false));
+ // @formatter:off
}
private void addRecordValue(final boolean lastRecord) {
- final String input = this.reusableToken.content.toString();
- final String inputClean = this.format.getTrim() ? input.trim() : input;
- if (lastRecord && inputClean.isEmpty() && this.format.getTrailingDelimiter()) {
+ final String input = format.trim(reusableToken.content.toString());
+ // Only drop the empty field produced by an actual trailing delimiter. A quoted empty
+ // field ("") is a real value, not a trailing delimiter, so it must be kept.
+ if (lastRecord && input.isEmpty() && format.getTrailingDelimiter() && !reusableToken.isQuoted) {
return;
}
- final String nullString = this.format.getNullString();
- this.recordList.add(inputClean.equals(nullString) ? null : inputClean);
+ recordList.add(handleNull(input));
}
/**
@@ -379,29 +596,97 @@ private void addRecordValue(final boolean lastRecord) {
*/
@Override
public void close() throws IOException {
- if (this.lexer != null) {
- this.lexer.close();
+ lexer.close();
+ }
+
+ private Map createEmptyHeaderMap() {
+ return format.getIgnoreHeaderCase() ?
+ new TreeMap<>(String.CASE_INSENSITIVE_ORDER) :
+ new LinkedHashMap<>();
+ }
+
+ /**
+ * Creates the name to index mapping if the format defines a header.
+ *
+ * @return null if the format has no header.
+ * @throws IOException if there is a problem reading the header or skipping the first record
+ * @throws CSVException on invalid input.
+ */
+ private Headers createHeaders() throws IOException {
+ Map headerMap = null;
+ List headerNames = null;
+ final String[] formatHeader = format.getHeader();
+ if (formatHeader != null) {
+ headerMap = createEmptyHeaderMap();
+ String[] headerRecord = null;
+ if (formatHeader.length == 0) {
+ // read the header from the first line of the file
+ final CSVRecord nextRecord = nextRecord();
+ if (nextRecord != null) {
+ headerRecord = nextRecord.values();
+ headerComment = nextRecord.getComment();
+ }
+ } else {
+ if (format.getSkipHeaderRecord()) {
+ final CSVRecord nextRecord = nextRecord();
+ if (nextRecord != null) {
+ headerComment = nextRecord.getComment();
+ }
+ }
+ headerRecord = formatHeader;
+ }
+ // build the name to index mappings
+ if (headerRecord != null) {
+ // Track an occurrence of a null, empty or blank header.
+ boolean observedMissing = false;
+ for (int i = 0; i < headerRecord.length; i++) {
+ final String header = headerRecord[i];
+ final boolean blankHeader = CSVFormat.isBlank(header);
+ if (blankHeader && !format.getAllowMissingColumnNames()) {
+ throw new IllegalArgumentException("A header name is missing in " + Arrays.toString(headerRecord));
+ }
+ final boolean containsHeader = blankHeader ? observedMissing : headerMap.containsKey(header);
+ final DuplicateHeaderMode headerMode = format.getDuplicateHeaderMode();
+ final boolean duplicatesAllowed = headerMode == DuplicateHeaderMode.ALLOW_ALL;
+ final boolean emptyDuplicatesAllowed = headerMode == DuplicateHeaderMode.ALLOW_EMPTY;
+ if (containsHeader && !duplicatesAllowed && !(blankHeader && emptyDuplicatesAllowed)) {
+ throw new IllegalArgumentException(String.format(
+ "The header contains a duplicate name: \"%s\" in %s. If this is valid then use CSVFormat.Builder.setDuplicateHeaderMode().",
+ header, Arrays.toString(headerRecord)));
+ }
+ observedMissing |= blankHeader;
+ if (header != null) {
+ headerMap.put(header, Integer.valueOf(i)); // Explicit boxing is intentional
+ if (headerNames == null) {
+ headerNames = new ArrayList<>(headerRecord.length);
+ }
+ headerNames.add(header);
+ }
+ }
+ }
}
+ // Make header names Collection immutable
+ return new Headers(headerMap, headerNames == null ? Collections.emptyList() : Collections.unmodifiableList(headerNames));
}
/**
- * Returns the current line number in the input stream.
+ * Gets the current line number in the input stream.
*
*
- * ATTENTION: If your CSV input has multi-line values, the returned number does not correspond to
+ * Note: If your CSV input has multi-line values, the returned number does not correspond to
* the record number.
*
*
- * @return current line number
+ * @return current line number.
*/
public long getCurrentLineNumber() {
- return this.lexer.getCurrentLineNumber();
+ return lexer.getCurrentLineNumber();
}
/**
* Gets the first end-of-line string encountered.
*
- * @return the first end-of-line string
+ * @return the first end-of-line string.
* @since 1.5
*/
public String getFirstEndOfLine() {
@@ -409,28 +694,74 @@ public String getFirstEndOfLine() {
}
/**
- * Returns a copy of the header map that iterates in column order.
+ * Gets the header comment, if any.
+ * The header comment appears before the header record.
+ *
+ * @return the header comment for this stream, or null if no comment is available.
+ * @since 1.10.0
+ */
+ public String getHeaderComment() {
+ return headerComment;
+ }
+
+ /**
+ * Gets a copy of the header map as defined in the CSVFormat's header.
*
* The map keys are column names. The map values are 0-based indices.
*
- * @return a copy of the header map that iterates in column order.
+ *
+ * Note: The map can only provide a one-to-one mapping when the format did not
+ * contain null or duplicate column names.
+ *
+ *
+ * @return a copy of the header map.
*/
public Map getHeaderMap() {
- return this.headerMap == null ? null : new LinkedHashMap<>(this.headerMap);
+ if (headers.headerMap == null) {
+ return null;
+ }
+ final Map map = createEmptyHeaderMap();
+ map.putAll(headers.headerMap);
+ return map;
}
/**
- * Returns the current record number in the input stream.
+ * Gets the underlying header map.
*
+ * @return the underlying header map.
+ */
+ Map getHeaderMapRaw() {
+ return headers.headerMap;
+ }
+
+ /**
+ * Gets a read-only list of header names that iterates in column order as defined in the CSVFormat's header.
*
- * ATTENTION: If your CSV input has multi-line values, the returned number does not correspond to
+ * Note: The list provides strings that can be used as keys in the header map.
+ * The list will not contain null column names if they were present in the input
+ * format.
+ *
+ *
+ * @return read-only list of header names that iterates in column order.
+ * @see #getHeaderMap()
+ * @since 1.7
+ */
+ public List getHeaderNames() {
+ return Collections.unmodifiableList(headers.headerNames);
+ }
+
+ /**
+ * Gets the current record number in the input stream.
+ *
+ *
+ * Note: If your CSV input has multi-line values, the returned number does not correspond to
* the line number.
*
*
* @return current record number
*/
public long getRecordNumber() {
- return this.recordNumber;
+ return recordNumber;
}
/**
@@ -440,190 +771,192 @@ public long getRecordNumber() {
*
* The returned content starts at the current parse-position in the stream.
*
+ *
+ * You can use {@link CSVFormat.Builder#setMaxRows(long)} to limit how many rows this method produces.
+ *
*
* @return list of {@link CSVRecord CSVRecords}, may be empty
- * @throws IOException
+ * @throws UncheckedIOException
* on parse error or input read-failure
*/
- public List getRecords() throws IOException {
- CSVRecord rec;
- final List records = new ArrayList<>();
- while ((rec = this.nextRecord()) != null) {
- records.add(rec);
- }
- return records;
+ public List getRecords() {
+ return stream().collect(Collectors.toList());
}
/**
- * Initializes the name to index mapping if the format defines a header.
+ * Gets the trailer comment, if any.
+ * Trailer comments are located between the last record and EOF
*
- * @return null if the format has no header.
- * @throws IOException if there is a problem reading the header or skipping the first record
+ * @return the trailer comment for this stream, or null if no comment is available.
+ * @since 1.10.0
*/
- private Map initializeHeader() throws IOException {
- Map hdrMap = null;
- final String[] formatHeader = this.format.getHeader();
- if (formatHeader != null) {
- hdrMap = this.format.getIgnoreHeaderCase() ?
- new TreeMap<>(String.CASE_INSENSITIVE_ORDER) :
- new LinkedHashMap<>();
-
- String[] headerRecord = null;
- if (formatHeader.length == 0) {
- // read the header from the first line of the file
- final CSVRecord nextRecord = this.nextRecord();
- if (nextRecord != null) {
- headerRecord = nextRecord.values();
- }
- } else {
- if (this.format.getSkipHeaderRecord()) {
- this.nextRecord();
- }
- headerRecord = formatHeader;
- }
+ public String getTrailerComment() {
+ return trailerComment;
+ }
- // build the name to index mappings
- if (headerRecord != null) {
- for (int i = 0; i < headerRecord.length; i++) {
- final String header = headerRecord[i];
- final boolean containsHeader = hdrMap.containsKey(header);
- final boolean emptyHeader = header == null || header.trim().isEmpty();
- if (containsHeader && (!emptyHeader || !this.format.getAllowMissingColumnNames())) {
- throw new IllegalArgumentException("The header contains a duplicate name: \"" + header +
- "\" in " + Arrays.toString(headerRecord));
- }
- hdrMap.put(header, Integer.valueOf(i));
- }
- }
+ /**
+ * Handles whether the input is parsed as null
+ *
+ * @param input
+ * the cell data to further processed
+ * @return null if input is parsed as null, or input itself if the input isn't parsed as null
+ */
+ private String handleNull(final String input) {
+ final boolean isQuoted = reusableToken.isQuoted;
+ final String nullString = format.getNullString();
+ final boolean strictQuoteMode = isStrictQuoteMode();
+ if (input.equals(nullString)) {
+ // nullString = NULL(String), distinguish between "NULL" and NULL in ALL_NON_NULL or NON_NUMERIC quote mode
+ return strictQuoteMode && isQuoted ? input : null;
}
- return hdrMap;
+ // don't set nullString, distinguish between "" and ,, (absent values) in All_NON_NULL or NON_NUMERIC quote mode
+ return strictQuoteMode && nullString == null && input.isEmpty() && !isQuoted ? null : input;
+ }
+
+ /**
+ * Checks whether there is a header comment.
+ * The header comment appears before the header record.
+ * Note that if the parser's format has been given an explicit header
+ * (with {@link CSVFormat.Builder#setHeader(String... )} or another overload)
+ * and the header record is not being skipped
+ * ({@link CSVFormat.Builder#setSkipHeaderRecord} is false) then any initial comments
+ * will be associated with the first record, not the header.
+ *
+ * @return true if this parser has seen a header comment, false otherwise
+ * @since 1.10.0
+ */
+ public boolean hasHeaderComment() {
+ return headerComment != null;
}
/**
- * Gets whether this parser is closed.
+ * Checks whether there is a trailer comment.
+ * Trailer comments are located between the last record and EOF.
+ * The trailer comments will only be available after the parser has
+ * finished processing this stream.
+ *
+ * @return true if this parser has seen a trailer comment, false otherwise
+ * @since 1.10.0
+ */
+ public boolean hasTrailerComment() {
+ return trailerComment != null;
+ }
+
+ /**
+ * Tests whether this parser is closed.
*
* @return whether this parser is closed.
*/
public boolean isClosed() {
- return this.lexer.isClosed();
+ return lexer.isClosed();
+ }
+
+ /**
+ * Tests whether the format's {@link QuoteMode} is {@link QuoteMode#ALL_NON_NULL} or {@link QuoteMode#NON_NUMERIC}.
+ *
+ * @return true if the format's {@link QuoteMode} is {@link QuoteMode#ALL_NON_NULL} or
+ * {@link QuoteMode#NON_NUMERIC}.
+ */
+ private boolean isStrictQuoteMode() {
+ return format.getQuoteMode() == QuoteMode.ALL_NON_NULL ||
+ format.getQuoteMode() == QuoteMode.NON_NUMERIC;
}
/**
- * Returns an iterator on the records.
+ * Returns the record iterator.
*
*
- * An {@link IOException} caught during the iteration are re-thrown as an
+ * An {@link IOException} caught during the iteration is re-thrown as an
* {@link IllegalStateException}.
*
*
- * If the parser is closed a call to {@link Iterator#next()} will throw a
+ * If the parser is closed, the iterator will not yield any more records.
+ * A call to {@link Iterator#hasNext()} will return {@code false} and
+ * a call to {@link Iterator#next()} will throw a
* {@link NoSuchElementException}.
*
+ *
+ * If it is necessary to construct an iterator which is usable after the
+ * parser is closed, one option is to extract all records as a list with
+ * {@link #getRecords()}, and return an iterator to that list.
+ *
+ *
+ * You can use {@link CSVFormat.Builder#setMaxRows(long)} to limit how many rows an Iterator produces.
+ *
*/
@Override
public Iterator iterator() {
return csvRecordIterator;
}
- class CSVRecordIterator implements Iterator {
- private CSVRecord current;
-
- private CSVRecord getNextRecord() {
- try {
- return CSVParser.this.nextRecord();
- } catch (final IOException e) {
- throw new IllegalStateException(
- e.getClass().getSimpleName() + " reading next record: " + e.toString(), e);
- }
- }
-
- @Override
- public boolean hasNext() {
- if (CSVParser.this.isClosed()) {
- return false;
- }
- if (this.current == null) {
- this.current = this.getNextRecord();
- }
-
- return this.current != null;
- }
-
- @Override
- public CSVRecord next() {
- if (CSVParser.this.isClosed()) {
- throw new NoSuchElementException("CSVParser has been closed");
- }
- CSVRecord next = this.current;
- this.current = null;
-
- if (next == null) {
- // hasNext() wasn't called before
- next = this.getNextRecord();
- if (next == null) {
- throw new NoSuchElementException("No more CSV records available");
- }
- }
-
- return next;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- }
-
/**
* Parses the next record from the current point in the stream.
*
- * @return the record as an array of values, or {@code null} if the end of the stream has been reached
- * @throws IOException
- * on parse error or input read-failure
+ * @return the record as an array of values, or {@code null} if the end of the stream has been reached.
+ * @throws IOException on parse error or input read-failure.
+ * @throws CSVException on invalid CSV input data.
*/
CSVRecord nextRecord() throws IOException {
CSVRecord result = null;
- this.recordList.clear();
+ recordList.clear();
StringBuilder sb = null;
- final long startCharPosition = lexer.getCharacterPosition() + this.characterOffset;
+ final long startCharPosition = lexer.getCharacterPosition() + characterOffset;
+ final long startBytePosition = lexer.getBytesRead() + byteOffset;
do {
- this.reusableToken.reset();
- this.lexer.nextToken(this.reusableToken);
- switch (this.reusableToken.type) {
+ reusableToken.reset();
+ lexer.nextToken(reusableToken);
+ switch (reusableToken.type) {
case TOKEN:
- this.addRecordValue(false);
+ addRecordValue(false);
break;
case EORECORD:
- this.addRecordValue(true);
+ addRecordValue(true);
break;
case EOF:
- if (this.reusableToken.isReady) {
- this.addRecordValue(true);
+ if (reusableToken.isReady) {
+ addRecordValue(true);
+ } else if (sb != null) {
+ trailerComment = sb.toString();
}
break;
case INVALID:
- throw new IOException("(line " + this.getCurrentLineNumber() + ") invalid parse sequence");
+ throw new CSVException("(line %,d) invalid parse sequence", getCurrentLineNumber());
case COMMENT: // Ignored currently
if (sb == null) { // first comment for this record
sb = new StringBuilder();
} else {
sb.append(Constants.LF);
}
- sb.append(this.reusableToken.content);
- this.reusableToken.type = TOKEN; // Read another token
+ sb.append(reusableToken.content);
+ reusableToken.type = TOKEN; // Read another token
break;
default:
- throw new IllegalStateException("Unexpected Token type: " + this.reusableToken.type);
+ throw new CSVException("Unexpected Token type: %s", reusableToken.type);
}
- } while (this.reusableToken.type == TOKEN);
-
- if (!this.recordList.isEmpty()) {
- this.recordNumber++;
- final String comment = sb == null ? null : sb.toString();
- result = new CSVRecord(this.recordList.toArray(new String[this.recordList.size()]), this.headerMap, comment,
- this.recordNumber, startCharPosition);
+ } while (reusableToken.type == TOKEN);
+ if (!recordList.isEmpty()) {
+ recordNumber++;
+ result = new CSVRecord(this, recordList.toArray(Constants.EMPTY_STRING_ARRAY), Objects.toString(sb, null), recordNumber, startCharPosition,
+ startBytePosition);
}
return result;
}
+ /**
+ * Returns a sequential {@code Stream} with this collection as its source.
+ *
+ * If the parser is closed, the stream will not produce any more values.
+ * See the comments in {@link #iterator()}.
+ *
+ *
+ * You can use {@link CSVFormat.Builder#setMaxRows(long)} to limit how many rows a Stream produces.
+ *
+ *
+ * @return a sequential {@code Stream} with this collection as its source.
+ * @since 1.9.0
+ */
+ public Stream stream() {
+ return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator(), Spliterator.ORDERED), false);
+ }
+
}
diff --git a/src/main/java/org/apache/commons/csv/CSVPrinter.java b/src/main/java/org/apache/commons/csv/CSVPrinter.java
index 12992f6797..a7048fd625 100644
--- a/src/main/java/org/apache/commons/csv/CSVPrinter.java
+++ b/src/main/java/org/apache/commons/csv/CSVPrinter.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
@@ -24,10 +26,19 @@
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.sql.Blob;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.sql.Statement;
import java.util.Arrays;
+import java.util.Objects;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.stream.Stream;
+
+import org.apache.commons.io.function.IOStream;
/**
* Prints values in a {@link CSVFormat CSV format}.
@@ -69,41 +80,41 @@
public final class CSVPrinter implements Flushable, Closeable {
/** The place that the values get written. */
- private final Appendable out;
+ private final Appendable appendable;
+
private final CSVFormat format;
/** True if we just began a new record. */
private boolean newRecord = true;
+ private long recordCount;
+
+ private final ReentrantLock lock = new ReentrantLock();
+
/**
* Creates a printer that will print values to the given stream following the CSVFormat.
*
- * Currently, only a pure encapsulation format or a pure escaping format is supported. Hybrid formats (encapsulation
- * and escaping with a different character) are not supported.
+ * Currently, only a pure encapsulation format or a pure escaping format is supported. Hybrid formats (encapsulation and escaping with a different
+ * character) are not supported.
*
*
- * @param out
- * stream to which to print. Must not be null.
- * @param format
- * the CSV format. Must not be null.
- * @throws IOException
- * thrown if the optional header cannot be printed.
- * @throws IllegalArgumentException
- * thrown if the parameters of the format are inconsistent or if either out or format are null.
+ * @param appendable stream to which to print. Must not be null.
+ * @param format the CSV format. Must not be null.
+ * @throws IOException thrown if the optional header cannot be printed.
+ * @throws IllegalArgumentException thrown if the parameters of the format are inconsistent.
+ * @throws NullPointerException thrown if either parameters are null.
*/
- public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException {
- Assertions.notNull(out, "out");
- Assertions.notNull(format, "format");
-
- this.out = out;
- this.format = format;
+ public CSVPrinter(final Appendable appendable, final CSVFormat format) throws IOException {
+ Objects.requireNonNull(appendable, "appendable");
+ Objects.requireNonNull(format, "format");
+ this.appendable = appendable;
+ this.format = format.copy();
// TODO: Is it a good idea to do this here instead of on the first call to a print method?
// It seems a pain to have to track whether the header has already been printed or not.
- if (format.getHeaderComments() != null) {
- for (final String line : format.getHeaderComments()) {
- if (line != null) {
- this.printComment(line);
- }
+ final String[] headerComments = format.getHeaderComments();
+ if (headerComments != null) {
+ for (final String line : headerComments) {
+ printComment(line);
}
}
if (format.getHeader() != null && !format.getSkipHeaderRecord()) {
@@ -111,10 +122,6 @@ public CSVPrinter(final Appendable out, final CSVFormat format) throws IOExcepti
}
}
- // ======================================================
- // printing implementation
- // ======================================================
-
@Override
public void close() throws IOException {
close(false);
@@ -122,21 +129,33 @@ public void close() throws IOException {
/**
* Closes the underlying stream with an optional flush first.
- * @param flush whether to flush before the actual close.
*
+ * @param flush whether to flush before the actual close.
* @throws IOException
* If an I/O error occurs
* @since 1.6
+ * @see CSVFormat#getAutoFlush()
*/
public void close(final boolean flush) throws IOException {
if (flush || format.getAutoFlush()) {
flush();
}
- if (out instanceof Closeable) {
- ((Closeable) out).close();
+ if (appendable instanceof Closeable) {
+ ((Closeable) appendable).close();
}
}
+ /**
+ * Prints the record separator and increments the record count.
+ *
+ * @throws IOException
+ * If an I/O error occurs
+ */
+ private void endOfRecord() throws IOException {
+ println();
+ recordCount++;
+ }
+
/**
* Flushes the underlying stream.
*
@@ -145,8 +164,8 @@ public void close(final boolean flush) throws IOException {
*/
@Override
public void flush() throws IOException {
- if (out instanceof Flushable) {
- ((Flushable) out).flush();
+ if (appendable instanceof Flushable) {
+ ((Flushable) appendable).flush();
}
}
@@ -156,7 +175,17 @@ public void flush() throws IOException {
* @return the target Appendable.
*/
public Appendable getOut() {
- return this.out;
+ return appendable;
+ }
+
+ /**
+ * Gets the record count printed, this does not include comments or headers.
+ *
+ * @return the record count, this does not include comments or headers.
+ * @since 1.13.0
+ */
+ public long getRecordCount() {
+ return recordCount;
}
/**
@@ -168,12 +197,16 @@ public Appendable getOut() {
* If an I/O error occurs
*/
public void print(final Object value) throws IOException {
- format.print(value, out, newRecord);
- newRecord = false;
+ lock.lock();
+ try {
+ printRaw(value);
+ } finally {
+ lock.unlock();
+ }
}
/**
- * Prints a comment on a new line among the delimiter separated values.
+ * Prints a comment on a new line among the delimiter-separated values.
*
*
* Comments will always begin on a new line and occupy at least one full line. The character specified to start
@@ -186,7 +219,7 @@ public void print(final Object value) throws IOException {
*
*
This method detects line breaks inside the comment string and inserts {@link CSVFormat#getRecordSeparator()}
* to start a new line of the comment. Note that this might produce unexpected results for formats that do not use
- * line breaks as record separator.
+ * line breaks as record separators.
*
* @param comment
* the comment to output
@@ -194,48 +227,91 @@ public void print(final Object value) throws IOException {
* If an I/O error occurs
*/
public void printComment(final String comment) throws IOException {
- if (!format.isCommentMarkerSet()) {
- return;
- }
- if (!newRecord) {
+ lock.lock();
+ try {
+ if (comment == null || !format.isCommentMarkerSet()) {
+ return;
+ }
+ if (!newRecord) {
+ println();
+ }
+ appendable.append(format.getCommentMarker().charValue()); // Explicit unboxing is intentional
+ appendable.append(SP);
+ for (int i = 0; i < comment.length(); i++) {
+ final char c = comment.charAt(i);
+ switch (c) {
+ case CR:
+ if (i + 1 < comment.length() && comment.charAt(i + 1) == LF) {
+ i++;
+ }
+ // falls-through: break intentionally excluded.
+ case LF:
+ println();
+ appendable.append(format.getCommentMarker().charValue()); // Explicit unboxing is intentional
+ appendable.append(SP);
+ break;
+ default:
+ appendable.append(c);
+ break;
+ }
+ }
println();
+ } finally {
+ lock.unlock();
}
- out.append(format.getCommentMarker().charValue());
- out.append(SP);
- for (int i = 0; i < comment.length(); i++) {
- final char c = comment.charAt(i);
- switch (c) {
- case CR:
- if (i + 1 < comment.length() && comment.charAt(i + 1) == LF) {
- i++;
- }
- //$FALL-THROUGH$ break intentionally excluded.
- case LF:
- println();
- out.append(format.getCommentMarker().charValue());
- out.append(SP);
- break;
- default:
- out.append(c);
- break;
+ }
+
+ /**
+ * Prints headers for a result set based on its metadata.
+ *
+ * @param resultSet The ResultSet to query for metadata.
+ * @throws IOException If an I/O error occurs.
+ * @throws SQLException If a database access error occurs or this method is called on a closed result set.
+ * @since 1.9.0
+ */
+ public void printHeaders(final ResultSet resultSet) throws IOException, SQLException {
+ lock.lock();
+ try {
+ try (IOStream stream = IOStream.of(format.builder().setHeader(resultSet).get().getHeader())) {
+ stream.forEachOrdered(this::print);
}
+ println();
+ } finally {
+ lock.unlock();
}
- println();
}
/**
- * Outputs the record separator.
+ * Prints the record separator.
*
* @throws IOException
* If an I/O error occurs
*/
public void println() throws IOException {
- format.println(out);
- newRecord = true;
+ lock.lock();
+ try {
+ format.println(appendable);
+ newRecord = true;
+ } finally {
+ lock.unlock();
+ }
}
/**
- * Prints the given values a single record of delimiter separated values followed by the record separator.
+ * Prints the string as the next value on the line. The value will be escaped or encapsulated as needed.
+ *
+ * @param value
+ * value to be output.
+ * @throws IOException
+ * If an I/O error occurs
+ */
+ private void printRaw(final Object value) throws IOException {
+ format.print(value, appendable, newRecord);
+ newRecord = false;
+ }
+
+ /**
+ * Prints the given values as a single record of delimiter-separated values followed by the record separator.
*
*
* The values will be quoted if needed. Quotes and newLine characters will be escaped. This method adds the record
@@ -247,15 +323,19 @@ public void println() throws IOException {
* @throws IOException
* If an I/O error occurs
*/
+ @SuppressWarnings("resource")
public void printRecord(final Iterable> values) throws IOException {
- for (final Object value : values) {
- print(value);
+ lock.lock();
+ try {
+ IOStream.of(values).forEachOrdered(this::print);
+ endOfRecord();
+ } finally {
+ lock.unlock();
}
- println();
}
/**
- * Prints the given values a single record of delimiter separated values followed by the record separator.
+ * Prints the given values as a single record of delimiter-separated values followed by the record separator.
*
*
* The values will be quoted if needed. Quotes and newLine characters will be escaped. This method adds the record
@@ -268,16 +348,55 @@ public void printRecord(final Iterable> values) throws IOException {
* If an I/O error occurs
*/
public void printRecord(final Object... values) throws IOException {
- format.printRecord(out, values);
- newRecord = true;
+ printRecord(Arrays.asList(values));
}
/**
- * Prints all the objects in the given collection handling nested collections/arrays as records.
+ * Prints the given values as a single record of delimiter-separated values followed by the record separator.
*
*
- * If the given collection only contains simple objects, this method will print a single record like
- * {@link #printRecord(Iterable)}. If the given collections contains nested collections/arrays those nested elements
+ * The values will be quoted if needed. Quotes and newLine characters will be escaped. This method adds the record
+ * separator to the output after printing the record, so there is no need to call {@link #println()}.
+ *
+ * If the given Iterable only contains simple objects, this method will print a single record like
+ * {@link #printRecord(Iterable)}. If the given Iterable contains nested collections/arrays those nested elements
* will each be printed as records using {@link #printRecord(Object...)}.
*
*
@@ -285,13 +404,12 @@ public void printRecord(final Object... values) throws IOException {
* Given the following data structure:
*
* If the given array only contains simple objects, this method will print a single record like
- * {@link #printRecord(Object...)}. If the given collections contains nested collections/arrays those nested
+ * {@link #printRecord(Object...)}. If the given collections contain nested collections or arrays, those nested
* elements will each be printed as records using {@link #printRecord(Object...)}.
*
*
@@ -336,25 +447,23 @@ public void printRecords(final Iterable> values) throws IOException {
* Given the following data structure:
*
*
- *
- *
+ *
{@code
* String[][] data = new String[3][]
* data[0] = String[]{ "A", "B", "C" };
* data[1] = new String[]{ "1", "2", "3" };
* data[2] = new String[]{ "A1", "B2", "C3" };
- *
+ * }
*
*
*
* Calling this method will print:
*
*
- *
- *
+ *
{@code
* A, B, C
* 1, 2, 3
* A1, B2, C3
- *
+ * }
*
*
* @param values
@@ -368,22 +477,103 @@ public void printRecords(final Object... values) throws IOException {
/**
* Prints all the objects in the given JDBC result set.
+ *
+ * You can use {@link CSVFormat.Builder#setMaxRows(long)} to limit how many rows a result set produces. This is most useful when you cannot limit rows
+ * through {@link Statement#setLargeMaxRows(long)} or {@link Statement#setMaxRows(int)}.
+ *
*
- * @param resultSet
- * result set the values to print.
- * @throws IOException
- * If an I/O error occurs
- * @throws SQLException
- * if a database access error occurs
+ * @param resultSet The values to print.
+ * @throws IOException If an I/O error occurs.
+ * @throws SQLException Thrown when a database access error occurs.
*/
public void printRecords(final ResultSet resultSet) throws SQLException, IOException {
final int columnCount = resultSet.getMetaData().getColumnCount();
- while (resultSet.next()) {
- for (int i = 1; i <= columnCount; i++) {
- final Object object = resultSet.getObject(i);
- print(object instanceof Clob ? ((Clob) object).getCharacterStream() : object);
+ while (resultSet.next() && format.useRow(resultSet.getRow())) {
+ lock.lock();
+ try {
+ for (int i = 1; i <= columnCount; i++) {
+ final Object object = resultSet.getObject(i);
+ if (object instanceof Clob) {
+ try (Reader reader = ((Clob) object).getCharacterStream()) {
+ print(reader);
+ }
+ } else if (object instanceof Blob) {
+ try (InputStream inputStream = ((Blob) object).getBinaryStream()) {
+ print(inputStream);
+ }
+ } else {
+ print(object);
+ }
+ }
+ endOfRecord();
+ } finally {
+ lock.unlock();
}
- println();
}
}
+
+ /**
+ * Prints all the objects with metadata in the given JDBC result set based on the header boolean.
+ *
+ * You can use {@link CSVFormat.Builder#setMaxRows(long)} to limit how many rows a result set produces. This is most useful when you cannot limit rows
+ * through {@link Statement#setLargeMaxRows(long)} or {@link Statement#setMaxRows(int)}.
+ *
+ *
+ * @param resultSet source of row data.
+ * @param printHeader whether to print headers.
+ * @throws IOException If an I/O error occurs
+ * @throws SQLException if a database access error occurs
+ * @since 1.9.0
+ */
+ public void printRecords(final ResultSet resultSet, final boolean printHeader) throws SQLException, IOException {
+ if (printHeader) {
+ printHeaders(resultSet);
+ }
+ printRecords(resultSet);
+ }
+
+ /**
+ * Prints all the objects in the given {@link Stream} handling nested collections/arrays as records.
+ *
+ *
+ * If the given Stream only contains simple objects, this method will print a single record like
+ * {@link #printRecord(Iterable)}. If the given Stream contains nested collections/arrays those nested elements
+ * will each be printed as records using {@link #printRecord(Object...)}.
+ *
+ *
+ * @param values
+ * the values to print.
+ * @throws IOException
+ * If an I/O error occurs
+ * @since 1.10.0
+ */
+ @SuppressWarnings({ "resource" }) // Caller closes.
+ public void printRecords(final Stream> values) throws IOException {
+ printRecords(IOStream.adapt(values));
+ }
}
diff --git a/src/main/java/org/apache/commons/csv/CSVRecord.java b/src/main/java/org/apache/commons/csv/CSVRecord.java
index 34a3ba2127..8dab14d907 100644
--- a/src/main/java/org/apache/commons/csv/CSVRecord.java
+++ b/src/main/java/org/apache/commons/csv/CSVRecord.java
@@ -1,60 +1,80 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
import java.io.Serializable;
import java.util.Arrays;
-import java.util.HashMap;
import java.util.Iterator;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import java.util.Map.Entry;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
/**
* A CSV record parsed from a CSV file.
+ *
+ *
+ * Note: Support for {@link Serializable} is scheduled to be removed in version 2.0.
+ * In version 1.8 the mapping between the column header and the column index was
+ * removed from the serialized state. The class maintains serialization compatibility
+ * with versions pre-1.8 for the record values; these must be accessed by index
+ * following deserialization. There will be a loss of any functionally linked to the header
+ * mapping when transferring serialized forms pre-1.8 to 1.8 and vice versa.
+ *
*/
public final class CSVRecord implements Serializable, Iterable {
- private static final String[] EMPTY_STRING_ARRAY = new String[0];
-
private static final long serialVersionUID = 1L;
+ /**
+ * The start position of this record as a character position in the source stream. This may or may not correspond to the byte position depending on the
+ * character set.
+ */
private final long characterPosition;
- /** The accumulated comments (if any) */
- private final String comment;
+ /**
+ * The starting position of this record in the source stream, measured in bytes.
+ */
+ private final long bytePosition;
- /** The column name to index mapping. */
- private final Map mapping;
+ /** The accumulated comments (if any). */
+ private final String comment;
/** The record number. */
private final long recordNumber;
- /** The values of the record */
+ /** The values of the record. */
private final String[] values;
- CSVRecord(final String[] values, final Map mapping, final String comment, final long recordNumber,
- final long characterPosition) {
+ /** The parser that originates this record. This is not serialized. */
+ private final transient CSVParser parser;
+
+ CSVRecord(final CSVParser parser, final String[] values, final String comment, final long recordNumber,
+ final long characterPosition, final long bytePosition) {
this.recordNumber = recordNumber;
- this.values = values != null ? values : EMPTY_STRING_ARRAY;
- this.mapping = mapping;
+ this.values = values != null ? values : Constants.EMPTY_STRING_ARRAY;
+ this.parser = parser;
this.comment = comment;
this.characterPosition = characterPosition;
+ this.bytePosition = bytePosition;
}
/**
@@ -65,7 +85,7 @@ public final class CSVRecord implements Serializable, Iterable {
* @return the String at the given enum String
*/
public String get(final Enum> e) {
- return get(e.toString());
+ return get(e == null ? null : e.name());
}
/**
@@ -80,37 +100,56 @@ public String get(final int i) {
}
/**
- * Returns a value by name.
+ * Returns a value by name. If multiple instances of the header name exists, only the last occurrence is returned.
+ *
+ *
+ * Note: This requires a field mapping obtained from the original parser.
+ * A check using {@link #isMapped(String)} should be used to determine if a
+ * mapping exists from the provided {@code name} to a field index. In this case an
+ * exception will only be thrown if the record does not contain a field corresponding
+ * to the mapping, that is the record length is not consistent with the mapping size.
+ *
*
* @param name
* the name of the column to be retrieved.
* @return the column value, maybe null depending on {@link CSVFormat#getNullString()}.
* @throws IllegalStateException
- * if no header mapping was provided
+ * if no header mapping was provided.
* @throws IllegalArgumentException
- * if {@code name} is not mapped or if the record is inconsistent
+ * if {@code name} is not mapped or if the record is inconsistent.
+ * @see #isMapped(String)
* @see #isConsistent()
- * @see CSVFormat#withNullString(String)
+ * @see #getParser()
+ * @see CSVFormat.Builder#setNullString(String)
*/
public String get(final String name) {
- if (mapping == null) {
- throw new IllegalStateException(
- "No header mapping was specified, the record values can't be accessed by name");
+ final Map headerMap = getHeaderMapRaw();
+ if (headerMap == null) {
+ throw new IllegalStateException("No header mapping was specified, the record values can't be accessed by name");
}
- final Integer index = mapping.get(name);
+ final Integer index = headerMap.get(name);
if (index == null) {
- throw new IllegalArgumentException(String.format("Mapping for %s not found, expected one of %s", name,
- mapping.keySet()));
+ throw new IllegalArgumentException(String.format("Mapping for %s not found, expected one of %s", name, headerMap.keySet()));
}
try {
- return values[index.intValue()];
+ return values[index.intValue()]; // Explicit unboxing is intentional
} catch (final ArrayIndexOutOfBoundsException e) {
- throw new IllegalArgumentException(String.format(
- "Index for header '%s' is %d but CSVRecord only has %d values!", name, index,
- Integer.valueOf(values.length)));
+ // Explicit boxing is intentional
+ throw new IllegalArgumentException(
+ String.format("Index for header '%s' is %d but CSVRecord only has %d values!", name, index, Integer.valueOf(values.length)));
}
}
+ /**
+ * Returns the starting position of this record in the source stream, measured in bytes.
+ *
+ * @return the byte position of this record in the source stream.
+ * @since 1.13.0
+ */
+ public long getBytePosition() {
+ return bytePosition;
+ }
+
/**
* Returns the start position of this record as a character position in the source stream. This may or may not
* correspond to the byte position depending on the character set.
@@ -124,8 +163,8 @@ public long getCharacterPosition() {
/**
* Returns the comment for this record, if any.
* Note that comments are attached to the following record.
- * If there is no following record (i.e. the comment is at EOF)
- * the comment will be ignored.
+ * If there is no following record (that is, the comment is at EOF),
+ * then the comment will be ignored.
*
* @return the comment for this record, or null if no comment for this record is available.
*/
@@ -133,11 +172,30 @@ public String getComment() {
return comment;
}
+ private Map getHeaderMapRaw() {
+ return parser == null ? null : parser.getHeaderMapRaw();
+ }
+
+ /**
+ * Returns the parser.
+ *
+ *
+ * Note: The parser is not part of the serialized state of the record. A null check
+ * should be used when the record may have originated from a serialized form.
+ *
+ *
+ * @return the parser.
+ * @since 1.7
+ */
+ public CSVParser getParser() {
+ return parser;
+ }
+
/**
* Returns the number of this record in the parsed CSV file.
*
*
- * ATTENTION: If your CSV input has multi-line values, the returned number does not correspond to
+ * NOTE:If your CSV input has multi-line values, the returned number does not correspond to
* the current line number of the parser that created this record.
*
*
@@ -148,6 +206,19 @@ public long getRecordNumber() {
return recordNumber;
}
+ /**
+ * Checks whether this record has a comment, false otherwise.
+ * Note that comments are attached to the following record.
+ * If there is no following record (that is, the comment is at EOF),
+ * then the comment will be ignored.
+ *
+ * @return true if this record has a comment, false otherwise.
+ * @since 1.3
+ */
+ public boolean hasComment() {
+ return comment != null;
+ }
+
/**
* Tells whether the record size matches the header size.
*
@@ -156,45 +227,45 @@ public long getRecordNumber() {
* test but still produce parsable files.
*
*
- * @return true of this record is valid, false if not
+ * @return true of this record is valid, false if not.
*/
public boolean isConsistent() {
- return mapping == null || mapping.size() == values.length;
+ final Map headerMap = getHeaderMapRaw();
+ return headerMap == null || headerMap.size() == values.length;
}
/**
- * Checks whether this record has a comment, false otherwise.
- * Note that comments are attached to the following record.
- * If there is no following record (i.e. the comment is at EOF)
- * the comment will be ignored.
+ * Checks whether a given column is mapped, that is, its name has been defined to the parser.
*
- * @return true if this record has a comment, false otherwise
- * @since 1.3
+ * @param name
+ * the name of the column to be retrieved.
+ * @return whether a given column is mapped.
*/
- public boolean hasComment() {
- return comment != null;
+ public boolean isMapped(final String name) {
+ final Map headerMap = getHeaderMapRaw();
+ return headerMap != null && headerMap.containsKey(name);
}
/**
- * Checks whether a given column is mapped, i.e. its name has been defined to the parser.
+ * Checks whether a column with a given index has a value.
*
- * @param name
- * the name of the column to be retrieved.
- * @return whether a given column is mapped.
+ * @param index
+ * a column index (0-based).
+ * @return whether a column with a given index has a value.
*/
- public boolean isMapped(final String name) {
- return mapping != null && mapping.containsKey(name);
+ public boolean isSet(final int index) {
+ return 0 <= index && index < values.length;
}
/**
- * Checks whether a given columns is mapped and has a value.
+ * Checks whether a given column is mapped and has a value.
*
* @param name
* the name of the column to be retrieved.
- * @return whether a given columns is mapped and has a value
+ * @return whether a given column is mapped and has a value.
*/
public boolean isSet(final String name) {
- return isMapped(name) && mapping.get(name).intValue() < values.length;
+ return isMapped(name) && getHeaderMapRaw().get(name).intValue() < values.length; // Explicit unboxing is intentional
}
/**
@@ -210,20 +281,20 @@ public Iterator iterator() {
/**
* Puts all values of this record into the given Map.
*
- * @param map
- * The Map to populate.
+ * @param The map type.
+ * @param map The Map to populate.
* @return the given map.
+ * @since 1.9.0
*/
- > M putIn(final M map) {
- if (mapping == null) {
+ public > M putIn(final M map) {
+ if (getHeaderMapRaw() == null) {
return map;
}
- for (final Entry entry : mapping.entrySet()) {
- final int col = entry.getValue().intValue();
- if (col < values.length) {
- map.put(entry.getKey(), values[col]);
+ getHeaderMapRaw().forEach((key, value) -> {
+ if (value < values.length) {
+ map.put(key, values[value]);
}
- }
+ });
return map;
}
@@ -237,23 +308,40 @@ public int size() {
}
/**
- * Converts the values to a List.
+ * Returns a sequential ordered stream whose elements are the values.
*
- * TODO: Maybe make this public?
+ * @return the new stream.
+ * @since 1.9.0
+ */
+ public Stream stream() {
+ return Stream.of(values);
+ }
+
+ /**
+ * Converts the values to a new List.
+ *
+ * Editing the list does not update this instance.
+ *
*
* @return a new List
+ * @since 1.9.0
*/
- private List toList() {
- return Arrays.asList(values);
+ public List toList() {
+ return stream().collect(Collectors.toList());
}
/**
- * Copies this record into a new Map. The new map is not connect
+ * Copies this record into a new Map of header name to record value. If multiple instances of a header name exist,
+ * then only the last occurrence is mapped.
+ *
+ *
+ * Editing the map does not update this instance.
+ *
*
* @return A new Map. The map is empty if the record has no headers.
*/
public Map toMap() {
- return putIn(new HashMap(values.length));
+ return putIn(new LinkedHashMap<>(values.length));
}
/**
@@ -264,12 +352,16 @@ public Map toMap() {
*/
@Override
public String toString() {
- return "CSVRecord [comment=" + comment + ", mapping=" + mapping +
- ", recordNumber=" + recordNumber + ", values=" +
- Arrays.toString(values) + "]";
+ return "CSVRecord [comment='" + comment + "', recordNumber=" + recordNumber + ", values=" + Arrays.toString(values) + "]";
}
- String[] values() {
+ /**
+ * Gets the values for this record. This is not a copy.
+ *
+ * @return the values for this record, never null.
+ * @since 1.10.0
+ */
+ public String[] values() {
return values;
}
diff --git a/src/main/java/org/apache/commons/csv/Constants.java b/src/main/java/org/apache/commons/csv/Constants.java
index b7dc770ac4..9dd276eccc 100644
--- a/src/main/java/org/apache/commons/csv/Constants.java
+++ b/src/main/java/org/apache/commons/csv/Constants.java
@@ -1,24 +1,26 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
/**
- * Constants for this package.
+ * Private constants for this package.
*/
final class Constants {
@@ -26,7 +28,7 @@ final class Constants {
static final char BACKSPACE = '\b';
- static final char COMMA = ',';
+ static final String COMMA = ",";
/**
* Starts a comment, the remainder of the line is the comment.
@@ -35,15 +37,14 @@ final class Constants {
static final char CR = '\r';
- /** RFC 4180 defines line breaks as CRLF */
+ /** RFC 4180 defines line breaks as CRLF. */
static final String CRLF = "\r\n";
- static final Character DOUBLE_QUOTE_CHAR = Character.valueOf('"');
+ static final Character DOUBLE_QUOTE_CHAR = Character.valueOf('"'); // Explicit boxing is intentional.
static final String EMPTY = "";
- /** The end of stream symbol */
- static final int END_OF_STREAM = -1;
+ static final String[] EMPTY_STRING_ARRAY = {};
static final char FF = '\f';
@@ -66,17 +67,24 @@ final class Constants {
static final char PIPE = '|';
- /** ASCII record separator */
+ /** ASCII record separator. */
static final char RS = 30;
static final char SP = ' ';
+ static final String SQL_NULL_STRING = "\\N";
+
static final char TAB = '\t';
- /** Undefined state for the lookahead char */
+ /** Undefined state for the lookahead char. */
static final int UNDEFINED = -2;
- /** ASCII unit separator */
+ /** ASCII unit separator. */
static final char US = 31;
+ /** No instances. */
+ private Constants() {
+ // noop
+ }
+
}
diff --git a/src/main/java/org/apache/commons/csv/DuplicateHeaderMode.java b/src/main/java/org/apache/commons/csv/DuplicateHeaderMode.java
new file mode 100644
index 0000000000..8087f16eeb
--- /dev/null
+++ b/src/main/java/org/apache/commons/csv/DuplicateHeaderMode.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.commons.csv;
+
+/**
+ * Enumerates how duplicate header fields should be handled
+ * if {@link CSVFormat.Builder#setHeader(Class)} is not null.
+ *
+ * @since 1.10.0
+ */
+public enum DuplicateHeaderMode {
+
+ /**
+ * Allows all duplicate headers.
+ */
+ ALLOW_ALL,
+
+ /**
+ * Allows duplicate headers only if they're empty, blank, or null strings.
+ */
+ ALLOW_EMPTY,
+
+ /**
+ * Disallows duplicate headers entirely.
+ */
+ DISALLOW
+}
diff --git a/src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java b/src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java
index 23a4042781..20c1ef5444 100644
--- a/src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java
+++ b/src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java
@@ -1,151 +1,176 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
import static org.apache.commons.csv.Constants.CR;
-import static org.apache.commons.csv.Constants.END_OF_STREAM;
import static org.apache.commons.csv.Constants.LF;
import static org.apache.commons.csv.Constants.UNDEFINED;
+import static org.apache.commons.io.IOUtils.EOF;
-import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.input.UnsynchronizedBufferedReader;
/**
* A special buffered reader which supports sophisticated read access.
*
- * In particular the reader supports a look-ahead option, which allows you to see the next char returned by
- * {@link #read()}. This reader also tracks how many characters have been read with {@link #getPosition()}.
+ * In particular the reader supports a look-ahead option, which allows you to see the next char returned by {@link #read()}. This reader also tracks how many
+ * characters have been read with {@link #getPosition()}.
*
*/
-final class ExtendedBufferedReader extends BufferedReader {
+final class ExtendedBufferedReader extends UnsynchronizedBufferedReader {
/** The last char returned */
private int lastChar = UNDEFINED;
+ private int lastCharMark = UNDEFINED;
+
/** The count of EOLs (CR/LF/CRLF) seen so far */
- private long eolCounter;
+ private long lineNumber;
- /** The position, which is number of characters read so far */
+ private long lineNumberMark;
+
+ /** The position, which is the number of characters read so far */
private long position;
- private boolean closed;
+ private long positionMark;
+
+ /** The number of bytes read so far. */
+ private long bytesRead;
+
+ private long bytesReadMark;
+
+ /** Encoder for calculating the number of bytes for each character read. */
+ private final CharsetEncoder encoder;
/**
- * Created extended buffered reader using default buffer-size
+ * Constructs a new instance using the default buffer size.
*/
ExtendedBufferedReader(final Reader reader) {
+ this(reader, null, false);
+ }
+
+ /**
+ * Constructs a new instance with the specified reader, character set, and byte tracking option. Initializes an encoder if byte tracking is enabled and a
+ * character set is provided.
+ *
+ * @param reader the reader supports a look-ahead option.
+ * @param charset the character set for encoding, or {@code null} if not applicable.
+ * @param trackBytes {@code true} to enable byte tracking; {@code false} to disable it.
+ */
+ ExtendedBufferedReader(final Reader reader, final Charset charset, final boolean trackBytes) {
super(reader);
+ encoder = charset != null && trackBytes ? charset.newEncoder() : null;
}
+ /**
+ * Closes the stream.
+ *
+ * @throws IOException If an I/O error occurs
+ */
@Override
- public int read() throws IOException {
- final int current = super.read();
- if (current == CR || current == LF && lastChar != CR) {
- eolCounter++;
- }
- lastChar = current;
- this.position++;
- return lastChar;
+ public void close() throws IOException {
+ // Set ivars before calling super close() in case close() throws an IOException.
+ lastChar = EOF;
+ super.close();
}
/**
- * Returns the last character that was read as an integer (0 to 65535). This will be the last character returned by
- * any of the read methods. This will not include a character read using the {@link #lookAhead()} method. If no
- * character has been read then this will return {@link Constants#UNDEFINED}. If the end of the stream was reached
- * on the last read then this will return {@link Constants#END_OF_STREAM}.
+ * Gets the number of bytes read by the reader.
*
- * @return the last character that was read
+ * @return the number of bytes read by the read
*/
- int getLastChar() {
- return lastChar;
+ long getBytesRead() {
+ return this.bytesRead;
}
- @Override
- public int read(final char[] buf, final int offset, final int length) throws IOException {
- if (length == 0) {
- return 0;
+ private long getEncodedCharLength(final char[] buf, final int offset, final int length) throws CharacterCodingException {
+ long len = 0;
+ int previous = lastChar;
+ for (int i = offset; i < offset + length; i++) {
+ len += getEncodedCharLength(previous, buf[i]);
+ previous = buf[i];
}
-
- final int len = super.read(buf, offset, length);
-
- if (len > 0) {
-
- for (int i = offset; i < offset + len; i++) {
- final char ch = buf[i];
- if (ch == LF) {
- if (CR != (i > 0 ? buf[i - 1] : lastChar)) {
- eolCounter++;
- }
- } else if (ch == CR) {
- eolCounter++;
- }
- }
-
- lastChar = buf[offset + len - 1];
-
- } else if (len == -1) {
- lastChar = END_OF_STREAM;
- }
-
- position += len;
return len;
}
/**
- * Calls {@link BufferedReader#readLine()} which drops the line terminator(s). This method should only be called
- * when processing a comment, otherwise information can be lost.
- *
- * Increments {@link #eolCounter}
+ * Gets the byte length of the given character based on the original Unicode specification, which defined characters as fixed-width 16-bit entities.
*
- * Sets {@link #lastChar} to {@link Constants#END_OF_STREAM} at EOF, otherwise to LF
+ * The Unicode characters are divided into two main ranges:
+ *
+ *
U+0000 to U+FFFF (Basic Multilingual Plane, BMP):
+ *
+ *
Represented using a single 16-bit {@code char}.
+ *
Includes UTF-8 encodings of 1-byte, 2-byte, and some 3-byte characters.
+ *
+ *
+ *
U+10000 to U+10FFFF (Supplementary Characters):
+ *
+ *
Represented as a pair of {@code char}s:
+ *
The first {@code char} is from the high-surrogates range (\uD800-\uDBFF).
+ *
The second {@code char} is from the low-surrogates range (\uDC00-\uDFFF).
+ *
Includes UTF-8 encodings of some 3-byte characters and all 4-byte characters.
+ *
+ *
+ *
*
- * @return the line that was read, or null if reached EOF.
+ * @param current the current character to process.
+ * @return the byte length of the character.
+ * @throws CharacterCodingException if the character cannot be encoded.
*/
- @Override
- public String readLine() throws IOException {
- final String line = super.readLine();
+ private int getEncodedCharLength(final int current) throws CharacterCodingException {
+ return getEncodedCharLength(lastChar, current);
+ }
- if (line != null) {
- lastChar = LF; // needed for detecting start of line
- eolCounter++;
- } else {
- lastChar = END_OF_STREAM;
+ private int getEncodedCharLength(final int previous, final int current) throws CharacterCodingException {
+ final char cChar = (char) current;
+ final char lChar = (char) previous;
+ if (!Character.isSurrogate(cChar)) {
+ return encoder.encode(CharBuffer.wrap(new char[] { cChar })).limit();
}
-
- return line;
+ if (Character.isHighSurrogate(cChar)) {
+ // Move on to the next char (low surrogate)
+ return 0;
+ }
+ if (Character.isSurrogatePair(lChar, cChar)) {
+ return encoder.encode(CharBuffer.wrap(new char[] { lChar, cChar })).limit();
+ }
+ throw new CharacterCodingException();
}
/**
- * Returns the next character in the current reader without consuming it. So the next call to {@link #read()} will
- * still return this value. Does not affect line number or last character.
+ * Returns the last character that was read as an integer (0 to 65535). This will be the last character returned by any of the read methods. This will not
+ * include a character read using the {@link #peek()} method. If no character has been read then this will return {@link Constants#UNDEFINED}. If the end of
+ * the stream was reached on the last read then this will return {@link IOUtils#EOF}.
*
- * @return the next character
- *
- * @throws IOException
- * if there is an error in reading
+ * @return the last character that was read
*/
- int lookAhead() throws IOException {
- super.mark(1);
- final int c = super.read();
- super.reset();
-
- return c;
+ int getLastChar() {
+ return lastChar;
}
/**
@@ -153,12 +178,12 @@ int lookAhead() throws IOException {
*
* @return the current line number
*/
- long getCurrentLineNumber() {
+ long getLineNumber() {
// Check if we are at EOL or EOF or just starting
- if (lastChar == CR || lastChar == LF || lastChar == UNDEFINED || lastChar == END_OF_STREAM) {
- return eolCounter; // counter is accurate
+ if (lastChar == CR || lastChar == LF || lastChar == UNDEFINED || lastChar == EOF) {
+ return lineNumber; // counter is accurate
}
- return eolCounter + 1; // Allow for counter being incremented only at EOL
+ return lineNumber + 1; // Allow for counter being incremented only at EOL
}
/**
@@ -170,22 +195,96 @@ long getPosition() {
return this.position;
}
- public boolean isClosed() {
- return closed;
+ @Override
+ public void mark(final int readAheadLimit) throws IOException {
+ lineNumberMark = lineNumber;
+ lastCharMark = lastChar;
+ positionMark = position;
+ bytesReadMark = bytesRead;
+ super.mark(readAheadLimit);
+ }
+
+ @Override
+ public int read() throws IOException {
+ final int current = super.read();
+ if (current == CR || current == LF && lastChar != CR || current == EOF && lastChar != CR && lastChar != LF && lastChar != EOF) {
+ lineNumber++;
+ }
+ if (encoder != null && current != EOF) {
+ this.bytesRead += getEncodedCharLength(current);
+ }
+ lastChar = current;
+ position++;
+ return lastChar;
+ }
+
+ @Override
+ public int read(final char[] buf, final int offset, final int length) throws IOException {
+ if (length == 0) {
+ return 0;
+ }
+ final int len = super.read(buf, offset, length);
+ if (encoder != null && len > 0) {
+ this.bytesRead += getEncodedCharLength(buf, offset, len);
+ }
+ if (len > 0) {
+ for (int i = offset; i < offset + len; i++) {
+ final char ch = buf[i];
+ if (ch == LF) {
+ if (CR != (i > offset ? buf[i - 1] : lastChar)) {
+ lineNumber++;
+ }
+ } else if (ch == CR) {
+ lineNumber++;
+ }
+ }
+ lastChar = buf[offset + len - 1];
+ } else if (len == EOF) {
+ lastChar = EOF;
+ }
+ position += len;
+ return len;
}
/**
- * Closes the stream.
+ * Gets the next line, dropping the line terminator(s). This method should only be called when processing a comment, otherwise, information can be lost.
+ *
+ * Sets {@link #lastChar} to {@code Constants.EOF} at EOF, otherwise the last EOL character.
+ *
*
- * @throws IOException
- * If an I/O error occurs
+ * @return the line that was read, or null if reached EOF.
*/
@Override
- public void close() throws IOException {
- // Set ivars before calling super close() in case close() throws an IOException.
- closed = true;
- lastChar = END_OF_STREAM;
- super.close();
+ public String readLine() throws IOException {
+ if (peek() == EOF) {
+ return null;
+ }
+ final StringBuilder buffer = new StringBuilder();
+ while (true) {
+ final int current = read();
+ if (current == CR) {
+ final int next = peek();
+ if (next == LF) {
+ read();
+ }
+ }
+ if (current == EOF || current == LF || current == CR) {
+ break;
+ }
+ buffer.append((char) current);
+ }
+ return buffer.toString();
}
+ @Override
+ public void reset() throws IOException {
+ lineNumber = lineNumberMark;
+ lastChar = lastCharMark;
+ position = positionMark;
+ bytesRead = bytesReadMark;
+ super.reset();
+ }
}
diff --git a/src/main/java/org/apache/commons/csv/IOUtils.java b/src/main/java/org/apache/commons/csv/IOUtils.java
deleted file mode 100644
index e82fb04979..0000000000
--- a/src/main/java/org/apache/commons/csv/IOUtils.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.csv;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.Writer;
-import java.nio.CharBuffer;
-
-/** Copied from Apache Commons IO. */
-class IOUtils {
-
- /**
- *
- * Copied from Apache Commons IO.
- *
- * The default buffer size ({@value}).
- */
- static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
-
- /**
- *
- * Copied from Apache Commons IO.
- *
- * Represents the end-of-file (or stream).
- * @since 2.5 (made public)
- */
- private static final int EOF = -1;
-
- /**
- * Copies chars from a large (over 2GB) Reader to an Appendable.
- *
- * This method buffers the input internally, so there is no need to use a
- * BufferedReader.
- *
- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
- *
- * @param input the Reader to read from
- * @param output the Appendable to append to
- * @return the number of characters copied
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since 2.7
- */
- static long copy(final Reader input, final Appendable output) throws IOException {
- return copy(input, output, CharBuffer.allocate(DEFAULT_BUFFER_SIZE));
- }
-
- /**
- * Copies chars from a large (over 2GB) Reader to an Appendable.
- *
- * This method uses the provided buffer, so there is no need to use a
- * BufferedReader.
- *
- *
- * @param input the Reader to read from
- * @param output the Appendable to write to
- * @param buffer the buffer to be used for the copy
- * @return the number of characters copied
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since 2.7
- */
- static long copy(final Reader input, final Appendable output, final CharBuffer buffer) throws IOException {
- long count = 0;
- int n;
- while (EOF != (n = input.read(buffer))) {
- buffer.flip();
- output.append(buffer, 0, n);
- count += n;
- }
- return count;
- }
-
- /**
- *
- * Copied from Apache Commons IO.
- *
- * Copies chars from a large (over 2GB) Reader to a Writer.
- *
- * This method buffers the input internally, so there is no need to use a
- * BufferedReader.
- *
- * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
- *
- * @param input the Reader to read from
- * @param output the Writer to write to
- * @return the number of characters copied
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since 1.3
- */
- static long copyLarge(final Reader input, final Writer output) throws IOException {
- return copyLarge(input, output, new char[DEFAULT_BUFFER_SIZE]);
- }
-
- /**
- *
- * Copied from Apache Commons IO.
- *
- * Copies chars from a large (over 2GB) Reader to a Writer.
- *
- * This method uses the provided buffer, so there is no need to use a
- * BufferedReader.
- *
- *
- * @param input the Reader to read from
- * @param output the Writer to write to
- * @param buffer the buffer to be used for the copy
- * @return the number of characters copied
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since 2.2
- */
- static long copyLarge(final Reader input, final Writer output, final char[] buffer) throws IOException {
- long count = 0;
- int n;
- while (EOF != (n = input.read(buffer))) {
- output.write(buffer, 0, n);
- count += n;
- }
- return count;
- }
-
-}
diff --git a/src/main/java/org/apache/commons/csv/Lexer.java b/src/main/java/org/apache/commons/csv/Lexer.java
index b29fc146aa..fe964480a4 100644
--- a/src/main/java/org/apache/commons/csv/Lexer.java
+++ b/src/main/java/org/apache/commons/csv/Lexer.java
@@ -1,77 +1,227 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
-import static org.apache.commons.csv.Constants.BACKSPACE;
-import static org.apache.commons.csv.Constants.CR;
-import static org.apache.commons.csv.Constants.END_OF_STREAM;
-import static org.apache.commons.csv.Constants.FF;
-import static org.apache.commons.csv.Constants.LF;
-import static org.apache.commons.csv.Constants.TAB;
-import static org.apache.commons.csv.Constants.UNDEFINED;
-import static org.apache.commons.csv.Token.Type.COMMENT;
-import static org.apache.commons.csv.Token.Type.EOF;
-import static org.apache.commons.csv.Token.Type.EORECORD;
-import static org.apache.commons.csv.Token.Type.INVALID;
-import static org.apache.commons.csv.Token.Type.TOKEN;
+import static org.apache.commons.io.IOUtils.EOF;
import java.io.Closeable;
import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.commons.io.IOUtils;
/**
* Lexical analyzer.
*/
final class Lexer implements Closeable {
- private static final String CR_STRING = Character.toString(CR);
- private static final String LF_STRING = Character.toString(LF);
-
- /**
- * Constant char to use for disabling comments, escapes and encapsulation. The value -2 is used because it
- * won't be confused with an EOF signal (-1), and because the Unicode value {@code FFFE} would be encoded as two
- * chars (using surrogates) and thus there should never be a collision with a real text char.
- */
- private static final char DISABLED = '\ufffe';
-
- private final char delimiter;
- private final char escape;
- private final char quoteChar;
- private final char commentStart;
+ private static final String CR_STRING = Character.toString(Constants.CR);
+ private static final String LF_STRING = Character.toString(Constants.LF);
+ private final char[] delimiter;
+ private final char[] delimiterBuf;
+ private final char[] escapeDelimiterBuf;
+ private final int escape;
+ private final int quoteChar;
+ private final int commentStart;
private final boolean ignoreSurroundingSpaces;
private final boolean ignoreEmptyLines;
+ private final boolean lenientEof;
+ private final boolean trailingData;
- /** The input stream */
+ /** The buffered reader. */
private final ExtendedBufferedReader reader;
private String firstEol;
- String getFirstEol(){
- return firstEol;
- }
+ private boolean isLastTokenDelimiter;
Lexer(final CSVFormat format, final ExtendedBufferedReader reader) {
this.reader = reader;
- this.delimiter = format.getDelimiter();
- this.escape = mapNullToDisabled(format.getEscapeCharacter());
- this.quoteChar = mapNullToDisabled(format.getQuoteCharacter());
- this.commentStart = mapNullToDisabled(format.getCommentMarker());
+ this.delimiter = format.getDelimiterCharArray();
+ this.escape = nullToDisabled(format.getEscapeCharacter());
+ this.quoteChar = nullToDisabled(format.getQuoteCharacter());
+ this.commentStart = nullToDisabled(format.getCommentMarker());
this.ignoreSurroundingSpaces = format.getIgnoreSurroundingSpaces();
this.ignoreEmptyLines = format.getIgnoreEmptyLines();
+ this.lenientEof = format.getLenientEof();
+ this.trailingData = format.getTrailingData();
+ this.delimiterBuf = new char[delimiter.length - 1];
+ this.escapeDelimiterBuf = new char[2 * delimiter.length - 1];
+ }
+
+ /**
+ * Appends the next escaped character to the token's content.
+ *
+ * @param token the current token.
+ * @throws IOException on stream access error.
+ * @throws CSVException Thrown on invalid input.
+ */
+ private void appendNextEscapedCharacterToToken(final Token token) throws IOException {
+ if (isEscapeDelimiter()) {
+ token.content.append(delimiter);
+ } else {
+ final int unescaped = readEscape();
+ if (unescaped == EOF) { // unexpected char after escape
+ token.content.append((char) escape).append((char) reader.getLastChar());
+ } else {
+ token.content.append((char) unescaped);
+ }
+ }
+ }
+
+ /**
+ * Closes resources.
+ *
+ * @throws IOException
+ * If an I/O error occurs.
+ */
+ @Override
+ public void close() throws IOException {
+ reader.close();
+ }
+
+ /**
+ * Gets the number of bytes read.
+ *
+ * @return the number of bytes read.
+ */
+ long getBytesRead() {
+ return reader.getBytesRead();
+ }
+
+ /**
+ * Gets the current character position.
+ *
+ * @return the current character position.
+ */
+ long getCharacterPosition() {
+ return reader.getPosition();
+ }
+
+ /**
+ * Gets the current line number.
+ *
+ * @return the current line number.
+ */
+ long getCurrentLineNumber() {
+ return reader.getLineNumber();
+ }
+
+ String getFirstEol() {
+ return firstEol;
+ }
+
+ boolean isClosed() {
+ return reader.isClosed();
+ }
+
+ boolean isCommentStart(final int ch) {
+ return ch == commentStart;
+ }
+
+ /**
+ * Tests whether the next characters constitute a delimiter through {@link ExtendedBufferedReader#peek(char[])}.
+ *
+ * @param ch
+ * the current character.
+ * @return true if the next characters constitute a delimiter.
+ * @throws IOException If an I/O error occurs.
+ */
+ boolean isDelimiter(final int ch) throws IOException {
+ isLastTokenDelimiter = false;
+ if (ch != delimiter[0]) {
+ return false;
+ }
+ if (delimiter.length == 1) {
+ isLastTokenDelimiter = true;
+ return true;
+ }
+ Arrays.fill(delimiterBuf, '\0');
+ reader.peek(delimiterBuf);
+ for (int i = 0; i < delimiterBuf.length; i++) {
+ if (delimiterBuf[i] != delimiter[i + 1]) {
+ return false;
+ }
+ }
+ final int count = reader.read(delimiterBuf, 0, delimiterBuf.length);
+ isLastTokenDelimiter = count != EOF;
+ return isLastTokenDelimiter;
+ }
+
+ /**
+ * Tests if the given character indicates the end of the file.
+ *
+ * @return true if the given character indicates the end of the file.
+ */
+ boolean isEndOfFile(final int ch) {
+ return ch == EOF;
+ }
+
+ /**
+ * Tests if the given character is the escape character.
+ *
+ * @return true if the given character is the escape character.
+ */
+ boolean isEscape(final int ch) {
+ return ch == escape;
+ }
+
+ /**
+ * Tests if the next characters constitute a escape delimiter through {@link ExtendedBufferedReader#peek(char[])}.
+ *
+ * For example, for delimiter "[|]" and escape '!', return true if the next characters constitute "![!|!]".
+ *
+ * @return true if the next characters constitute an escape delimiter.
+ * @throws IOException If an I/O error occurs.
+ */
+ boolean isEscapeDelimiter() throws IOException {
+ Arrays.fill(escapeDelimiterBuf, '\0');
+ reader.peek(escapeDelimiterBuf);
+ if (escapeDelimiterBuf[0] != delimiter[0]) {
+ return false;
+ }
+ for (int i = 1; i < delimiter.length; i++) {
+ if (escapeDelimiterBuf[2 * i] != delimiter[i] || escapeDelimiterBuf[2 * i - 1] != escape) {
+ return false;
+ }
+ }
+ final int count = reader.read(escapeDelimiterBuf, 0, escapeDelimiterBuf.length);
+ return count != EOF;
+ }
+
+ private boolean isMetaChar(final int ch) {
+ return ch == escape || ch == quoteChar || ch == commentStart;
+ }
+
+ boolean isQuoteChar(final int ch) {
+ return ch == quoteChar;
+ }
+
+ /**
+ * Tests if the current character represents the start of a line: a CR, LF, or is at the start of the file.
+ *
+ * @param ch the character to check.
+ * @return true if the character is at the start of a line.
+ */
+ boolean isStartOfLine(final int ch) {
+ return ch == Constants.LF || ch == Constants.CR || ch == Constants.UNDEFINED;
}
/**
@@ -80,86 +230,82 @@ String getFirstEol(){
* A token corresponds to a term, a record change or an end-of-file indicator.
*
*
- * @param token
- * an existing Token object to reuse. The caller is responsible to initialize the Token.
- * @return the next token found
- * @throws java.io.IOException
- * on stream access error
+ * @param token an existing Token object to reuse. The caller is responsible for initializing the Token.
+ * @return the next token found.
+ * @throws IOException on stream access error.
+ * @throws CSVException Thrown on invalid input.
*/
Token nextToken(final Token token) throws IOException {
-
- // get the last read char (required for empty line detection)
+ // Get the last read char (required for empty line detection)
int lastChar = reader.getLastChar();
-
// read the next char and set eol
int c = reader.read();
- /*
- * Note: The following call will swallow LF if c == CR. But we don't need to know if the last char was CR or LF
- * - they are equivalent here.
- */
+ // Note: The following call will swallow LF if c == CR. But we don't need to know if the last char was CR or LF - they are equivalent here.
boolean eol = readEndOfLine(c);
-
// empty line detection: eol AND (last char was EOL or beginning)
if (ignoreEmptyLines) {
while (eol && isStartOfLine(lastChar)) {
- // go on char ahead ...
+ // Go on char ahead ...
lastChar = c;
c = reader.read();
eol = readEndOfLine(c);
- // reached end of file without any content (empty line at the end)
+ // reached the end of the file without any content (empty line at the end)
if (isEndOfFile(c)) {
- token.type = EOF;
+ token.type = Token.Type.EOF;
// don't set token.isReady here because no content
return token;
}
}
}
-
- // did we reach eof during the last iteration already ? EOF
- if (isEndOfFile(lastChar) || !isDelimiter(lastChar) && isEndOfFile(c)) {
- token.type = EOF;
+ // Did we reach EOF during the last iteration already? EOF
+ if (isEndOfFile(lastChar) || !isLastTokenDelimiter && isEndOfFile(c)) {
+ token.type = Token.Type.EOF;
// don't set token.isReady here because no content
return token;
}
-
if (isStartOfLine(lastChar) && isCommentStart(c)) {
final String line = reader.readLine();
if (line == null) {
- token.type = EOF;
+ token.type = Token.Type.EOF;
// don't set token.isReady here because no content
return token;
}
final String comment = line.trim();
token.content.append(comment);
- token.type = COMMENT;
+ token.type = Token.Type.COMMENT;
return token;
}
-
- // important: make sure a new char gets consumed in each iteration
- while (token.type == INVALID) {
+ // Important: make sure a new char gets consumed in each iteration
+ while (token.type == Token.Type.INVALID) {
+ // isDelimiter consumes the trailing characters of a multi-character delimiter as a side effect, so it must
+ // only be evaluated once per character. Remember a match found while skipping whitespace below.
+ boolean delimiter = false;
// ignore whitespaces at beginning of a token
if (ignoreSurroundingSpaces) {
- while (isWhitespace(c) && !eol) {
+ while (Character.isWhitespace((char) c) && !eol) {
+ if (isDelimiter(c)) {
+ delimiter = true;
+ break;
+ }
c = reader.read();
eol = readEndOfLine(c);
}
}
-
// ok, start of token reached: encapsulated, or token
- if (isDelimiter(c)) {
+ if (delimiter || isDelimiter(c)) {
// empty token return TOKEN("")
- token.type = TOKEN;
+ token.type = Token.Type.TOKEN;
} else if (eol) {
// empty token return EORECORD("")
// noop: token.content.append("");
- token.type = EORECORD;
+ token.type = Token.Type.EORECORD;
} else if (isQuoteChar(c)) {
// consume encapsulated token
parseEncapsulatedToken(token);
} else if (isEndOfFile(c)) {
// end of file return EOF()
// noop: token.content.append("");
- token.type = EOF;
+ token.type = Token.Type.EOF;
token.isReady = true; // there is data at EOF
} else {
// next token must be a simple token
@@ -170,67 +316,19 @@ Token nextToken(final Token token) throws IOException {
return token;
}
- /**
- * Parses a simple token.
- *
- * Simple token are tokens which are not surrounded by encapsulators. A simple token might contain escaped
- * delimiters (as \, or \;). The token is finished when one of the following conditions become true:
- *
- *
end of line has been reached (EORECORD)
- *
end of stream has been reached (EOF)
- *
an unescaped delimiter has been reached (TOKEN)
- *
- *
- * @param token
- * the current token
- * @param ch
- * the current character
- * @return the filled token
- * @throws IOException
- * on stream access error
- */
- private Token parseSimpleToken(final Token token, int ch) throws IOException {
- // Faster to use while(true)+break than while(token.type == INVALID)
- while (true) {
- if (readEndOfLine(ch)) {
- token.type = EORECORD;
- break;
- } else if (isEndOfFile(ch)) {
- token.type = EOF;
- token.isReady = true; // There is data at EOF
- break;
- } else if (isDelimiter(ch)) {
- token.type = TOKEN;
- break;
- } else if (isEscape(ch)) {
- final int unescaped = readEscape();
- if (unescaped == END_OF_STREAM) { // unexpected char after escape
- token.content.append((char) ch).append((char) reader.getLastChar());
- } else {
- token.content.append((char) unescaped);
- }
- ch = reader.read(); // continue
- } else {
- token.content.append((char) ch);
- ch = reader.read(); // continue
- }
- }
-
- if (ignoreSurroundingSpaces) {
- trimTrailingSpaces(token.content);
- }
-
- return token;
+ private int nullToDisabled(final Character c) {
+ return c == null ? Constants.UNDEFINED : c.charValue(); // Explicit unboxing
}
/**
* Parses an encapsulated token.
- *
- * Encapsulated tokens are surrounded by the given encapsulating-string. The encapsulator itself might be included
+ *
+ * Encapsulated tokens are surrounded by the given encapsulating string. The encapsulator itself might be included
* in the token using a doubling syntax (as "", '') or using escaping (as in \", \'). Whitespaces before and after
- * an encapsulated token are ignored. The token is finished when one of the following conditions become true:
+ * an encapsulated token is ignored. The token is finished when one of the following conditions becomes true:
+ *
*
- *
an unescaped encapsulator has been reached, and is followed by optional whitespace then:
+ *
An unescaped encapsulator has been reached and is followed by optional whitespace then:
*
*
delimiter (TOKEN)
*
end of line (EORECORD)
@@ -241,24 +339,19 @@ private Token parseSimpleToken(final Token token, int ch) throws IOException {
* the current token
* @return a valid token object
* @throws IOException
- * on invalid state: EOF before closing encapsulator or invalid character before delimiter or EOL
+ * Thrown when in an invalid state: EOF before closing encapsulator or invalid character before
+ * delimiter or EOL.
+ * @throws CSVException Thrown on invalid input.
*/
private Token parseEncapsulatedToken(final Token token) throws IOException {
- // save current line number in case needed for IOE
+ token.isQuoted = true;
+ // Save current line number in case needed for IOE
final long startLineNumber = getCurrentLineNumber();
int c;
while (true) {
c = reader.read();
-
- if (isEscape(c)) {
- final int unescaped = readEscape();
- if (unescaped == END_OF_STREAM) { // unexpected char after escape
- token.content.append((char) c).append((char) reader.getLastChar());
- } else {
- token.content.append((char) unescaped);
- }
- } else if (isQuoteChar(c)) {
- if (isQuoteChar(reader.lookAhead())) {
+ if (isQuoteChar(c)) {
+ if (isQuoteChar(reader.peek())) {
// double or escaped encapsulator -> add single encapsulator to token
c = reader.read();
token.content.append((char) c);
@@ -267,26 +360,37 @@ private Token parseEncapsulatedToken(final Token token) throws IOException {
while (true) {
c = reader.read();
if (isDelimiter(c)) {
- token.type = TOKEN;
+ token.type = Token.Type.TOKEN;
return token;
- } else if (isEndOfFile(c)) {
- token.type = EOF;
+ }
+ if (isEndOfFile(c)) {
+ token.type = Token.Type.EOF;
token.isReady = true; // There is data at EOF
return token;
- } else if (readEndOfLine(c)) {
- token.type = EORECORD;
+ }
+ if (readEndOfLine(c)) {
+ token.type = Token.Type.EORECORD;
return token;
- } else if (!isWhitespace(c)) {
+ }
+ if (trailingData) {
+ token.content.append((char) c);
+ } else if (!Character.isWhitespace((char) c)) {
// error invalid char between token and next delimiter
- throw new IOException("(line " + getCurrentLineNumber() +
- ") invalid char between encapsulated token and delimiter");
+ throw new CSVException("Invalid character between encapsulated token and delimiter at line: %,d, position: %,d",
+ getCurrentLineNumber(), getCharacterPosition());
}
}
}
+ } else if (isEscape(c)) {
+ appendNextEscapedCharacterToToken(token);
} else if (isEndOfFile(c)) {
+ if (lenientEof) {
+ token.type = Token.Type.EOF;
+ token.isReady = true; // There is data at EOF
+ return token;
+ }
// error condition (end of file before end of token)
- throw new IOException("(startline " + startLineNumber +
- ") EOF reached before encapsulated token finished");
+ throw new CSVException("(startline %,d) EOF reached before encapsulated token finished", startLineNumber);
} else {
// consume character
token.content.append((char) c);
@@ -294,168 +398,133 @@ private Token parseEncapsulatedToken(final Token token) throws IOException {
}
}
- private char mapNullToDisabled(final Character c) {
- return c == null ? DISABLED : c.charValue();
- }
-
/**
- * Returns the current line number
+ * Parses a simple token.
+ *
+ * Simple tokens are tokens that are not surrounded by encapsulators. A simple token might contain escaped delimiters (as \, or \;). The token is finished
+ * when one of the following conditions becomes true:
+ *
+ *
+ *
The end of line has been reached (EORECORD)
+ *
The end of stream has been reached (EOF)
+ *
An unescaped delimiter has been reached (TOKEN)
+ *
*
- * @return the current line number
+ * @param token the current token.
+ * @param ch the current character.
+ * @return the filled token.
+ * @throws IOException on stream access error.
+ * @throws CSVException Thrown on invalid input.
*/
- long getCurrentLineNumber() {
- return reader.getCurrentLineNumber();
+ private Token parseSimpleToken(final Token token, final int ch) throws IOException {
+ // Faster to use while(true)+break than while(token.type == INVALID)
+ int cur = ch;
+ while (true) {
+ if (readEndOfLine(cur)) {
+ token.type = Token.Type.EORECORD;
+ break;
+ }
+ if (isEndOfFile(cur)) {
+ token.type = Token.Type.EOF;
+ token.isReady = true; // There is data at EOF
+ break;
+ }
+ if (isDelimiter(cur)) {
+ token.type = Token.Type.TOKEN;
+ break;
+ }
+ // continue
+ if (isEscape(cur)) {
+ appendNextEscapedCharacterToToken(token);
+ } else {
+ token.content.append((char) cur);
+ }
+ cur = reader.read(); // continue
+ }
+
+ if (ignoreSurroundingSpaces) {
+ trimTrailingSpaces(token.content);
+ }
+
+ return token;
}
/**
- * Returns the current character position
+ * Greedily accepts \n, \r and \r\n This checker consumes silently the second control-character...
*
- * @return the current character position
+ * @return true if the given or next character is a line-terminator.
*/
- long getCharacterPosition() {
- return reader.getPosition();
+ boolean readEndOfLine(final int ch) throws IOException {
+ // check if we have \r\n...
+ int cur = ch;
+ if (cur == Constants.CR && reader.peek() == Constants.LF) {
+ // note: does not change ch outside of this method!
+ cur = reader.read();
+ // Save the EOL state
+ if (firstEol == null) {
+ this.firstEol = Constants.CRLF;
+ }
+ }
+ // save EOL state here.
+ if (firstEol == null) {
+ if (cur == Constants.LF) {
+ this.firstEol = LF_STRING;
+ } else if (cur == Constants.CR) {
+ this.firstEol = CR_STRING;
+ }
+ }
+
+ return cur == Constants.LF || cur == Constants.CR;
}
// TODO escape handling needs more work
/**
- * Handle an escape sequence.
- * The current character must be the escape character.
- * On return, the next character is available by calling {@link ExtendedBufferedReader#getLastChar()}
- * on the input stream.
+ * Handle an escape sequence. The current character must be the escape character. On return, the next character is available by calling
+ * {@link ExtendedBufferedReader#getLastChar()} on the input stream.
*
- * @return the unescaped character (as an int) or {@link Constants#END_OF_STREAM} if char following the escape is
- * invalid.
- * @throws IOException if there is a problem reading the stream or the end of stream is detected:
- * the escape character is not allowed at end of stream
+ * @return the unescaped character (as an int) or {@link IOUtils#EOF} if char following the escape is invalid.
+ * @throws IOException if there is a problem reading the stream or the end of stream is detected: the escape character is not allowed at end of stream
+ * @throws CSVException Thrown on invalid input.
*/
int readEscape() throws IOException {
// the escape char has just been read (normally a backslash)
final int ch = reader.read();
switch (ch) {
case 'r':
- return CR;
+ return Constants.CR;
case 'n':
- return LF;
+ return Constants.LF;
case 't':
- return TAB;
+ return Constants.TAB;
case 'b':
- return BACKSPACE;
+ return Constants.BACKSPACE;
case 'f':
- return FF;
- case CR:
- case LF:
- case FF: // TODO is this correct?
- case TAB: // TODO is this correct? Do tabs need to be escaped?
- case BACKSPACE: // TODO is this correct?
+ return Constants.FF;
+ case Constants.CR:
+ case Constants.LF:
+ case Constants.FF: // TODO is this correct?
+ case Constants.TAB: // TODO is this correct? Do tabs need to be escaped?
+ case Constants.BACKSPACE: // TODO is this correct?
return ch;
- case END_OF_STREAM:
- throw new IOException("EOF whilst processing escape sequence");
+ case EOF:
+ throw new CSVException("EOF while processing escape sequence");
default:
// Now check for meta-characters
if (isMetaChar(ch)) {
return ch;
}
// indicate unexpected char - available from in.getLastChar()
- return END_OF_STREAM;
+ return EOF;
}
}
void trimTrailingSpaces(final StringBuilder buffer) {
int length = buffer.length();
while (length > 0 && Character.isWhitespace(buffer.charAt(length - 1))) {
- length = length - 1;
+ length--;
}
if (length != buffer.length()) {
buffer.setLength(length);
}
}
-
- /**
- * Greedily accepts \n, \r and \r\n This checker consumes silently the second control-character...
- *
- * @return true if the given or next character is a line-terminator
- */
- boolean readEndOfLine(int ch) throws IOException {
- // check if we have \r\n...
- if (ch == CR && reader.lookAhead() == LF) {
- // note: does not change ch outside of this method!
- ch = reader.read();
- // Save the EOL state
- if (firstEol == null) {
- this.firstEol = Constants.CRLF;
- }
- }
- // save EOL state here.
- if (firstEol == null) {
- if (ch == LF) {
- this.firstEol = LF_STRING;
- } else if (ch == CR) {
- this.firstEol = CR_STRING;
- }
- }
-
- return ch == LF || ch == CR;
- }
-
- boolean isClosed() {
- return reader.isClosed();
- }
-
- /**
- * @return true if the given char is a whitespace character
- */
- boolean isWhitespace(final int ch) {
- return !isDelimiter(ch) && Character.isWhitespace((char) ch);
- }
-
- /**
- * Checks if the current character represents the start of a line: a CR, LF or is at the start of the file.
- *
- * @param ch the character to check
- * @return true if the character is at the start of a line.
- */
- boolean isStartOfLine(final int ch) {
- return ch == LF || ch == CR || ch == UNDEFINED;
- }
-
- /**
- * @return true if the given character indicates end of file
- */
- boolean isEndOfFile(final int ch) {
- return ch == END_OF_STREAM;
- }
-
- boolean isDelimiter(final int ch) {
- return ch == delimiter;
- }
-
- boolean isEscape(final int ch) {
- return ch == escape;
- }
-
- boolean isQuoteChar(final int ch) {
- return ch == quoteChar;
- }
-
- boolean isCommentStart(final int ch) {
- return ch == commentStart;
- }
-
- private boolean isMetaChar(final int ch) {
- return ch == delimiter ||
- ch == escape ||
- ch == quoteChar ||
- ch == commentStart;
- }
-
- /**
- * Closes resources.
- *
- * @throws IOException
- * If an I/O error occurs
- */
- @Override
- public void close() throws IOException {
- reader.close();
- }
}
diff --git a/src/main/java/org/apache/commons/csv/QuoteMode.java b/src/main/java/org/apache/commons/csv/QuoteMode.java
index 272deb7383..ae64ab4863 100644
--- a/src/main/java/org/apache/commons/csv/QuoteMode.java
+++ b/src/main/java/org/apache/commons/csv/QuoteMode.java
@@ -1,23 +1,27 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
/**
- * Defines quoting behavior when printing.
+ * Enumerates quoting behavior.
+ *
+ * @see CSVFormat.Builder#setQuoteMode(QuoteMode)
*/
public enum QuoteMode {
@@ -32,7 +36,7 @@ public enum QuoteMode {
ALL_NON_NULL,
/**
- * Quotes fields which contain special characters such as a the field delimiter, quote character or any of the
+ * Quotes fields that contain special characters such as a field delimiter, quote character, or any of the
* characters in the line separator string.
*/
MINIMAL,
diff --git a/src/main/java/org/apache/commons/csv/Token.java b/src/main/java/org/apache/commons/csv/Token.java
index 861e097d44..87af335678 100644
--- a/src/main/java/org/apache/commons/csv/Token.java
+++ b/src/main/java/org/apache/commons/csv/Token.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
@@ -21,19 +23,18 @@
/**
* Internal token representation.
- *
- * It is used as contract between the lexer and the parser.
+ *
+ * This is used as a contract between the lexer and the parser.
+ *
*/
final class Token {
- /** length of the initial token (content-)buffer */
- private static final int INITIAL_TOKEN_LENGTH = 50;
-
enum Type {
- /** Token has no valid content, i.e. is in its initialized state. */
+
+ /** Token has no valid content, that is, is in its initialized state. */
INVALID,
- /** Token with content, at beginning or in the middle of a line. */
+ /** Token with content, at the beginning or in the middle of a line. */
TOKEN,
/** Token (which can have content) when the end of file is reached. */
@@ -46,28 +47,34 @@ enum Type {
COMMENT
}
+ /** Length of the initial token (content-)buffer */
+ private static final int DEFAULT_CAPACITY = 50;
+
/** Token type */
Token.Type type = INVALID;
- /** The content buffer. */
- final StringBuilder content = new StringBuilder(INITIAL_TOKEN_LENGTH);
+ /** The content buffer, never null. */
+ final StringBuilder content = new StringBuilder(DEFAULT_CAPACITY);
/** Token ready flag: indicates a valid token with content (ready for the parser). */
boolean isReady;
+ boolean isQuoted;
+
void reset() {
content.setLength(0);
type = INVALID;
isReady = false;
+ isQuoted = false;
}
/**
- * Eases IDE debugging.
+ * Converts the token state to a string to ease debugging.
*
* @return a string helpful for debugging.
*/
@Override
public String toString() {
- return type.name() + " [" + content.toString() + "]";
+ return type + " [" + content.toString() + "]";
}
}
diff --git a/src/main/java/org/apache/commons/csv/package-info.java b/src/main/java/org/apache/commons/csv/package-info.java
index 29e7fef612..d3340fcae8 100644
--- a/src/main/java/org/apache/commons/csv/package-info.java
+++ b/src/main/java/org/apache/commons/csv/package-info.java
@@ -1,31 +1,33 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/**
- * Apache Commons CSV Format Support.
+ *
Apache Commons CSV
*
- *
CSV are widely used as interfaces to legacy systems or manual data-imports.
+ *
CSV are widely used as interfaces to legacy systems or manual data imports.
* CSV stands for "Comma Separated Values" (or sometimes "Character Separated
* Values"). The CSV data format is defined in
- * RFC 4180
+ * RFC 4180
* but many dialects exist.
*
*
Common to all file dialects is its basic structure: The CSV data-format
- * is record oriented, whereas each record starts on a new textual line. A
+ * is record-oriented, whereas each record starts on a new textual line. A
* record is build of a list of values. Keep in mind that not all records
* must have an equal number of values:
*
@@ -36,28 +38,28 @@
*
The following list contains the CSV aspects the Commons CSV parser supports:
*
*
Separators (for lines)
- *
The record separators are hardcoded and cannot be changed. The must be '\r', '\n' or '\r\n'.
+ *
The record separators are hardcoded and cannot be changed. The must be '\r', '\n', or '\r\n'.
*
*
Delimiter (for values)
*
The delimiter for values is freely configurable (default ',').
*
*
Comments
- *
Some CSV-dialects support a simple comment syntax. A comment is a record
+ *
Some CSV dialects support a simple comment syntax. A comment is a record
* which must start with a designated character (the commentStarter). A record
- * of this kind is treated as comment and gets removed from the input (default none)
+ * of this kind is treated as a comment and gets removed from the input (default none)
*
*
Encapsulator
*
Two encapsulator characters (default '"') are used to enclose -> complex values.
*
*
Simple values
- *
A simple value consist of all characters (except the delimiter) until
- * (but not including) the next delimiter or a record-terminator. Optionally
+ *
A simple value consists of all characters (except the delimiter) until
+ * (but not including) the next delimiter or a record terminator. Optionally
* all surrounding whitespaces of a simple value can be ignored (default: true).
*
*
Complex values
*
Complex values are encapsulated within a pair of the defined encapsulator characters.
* The encapsulator itself must be escaped or doubled when used inside complex values.
- * Complex values preserve all kind of formatting (including newlines -> multiline-values)
+ * Complex values preserve all kinds of formatting (including newlines -> multiline-values)
*
*
Empty line skipping
*
Optionally empty lines in CSV files can be skipped.
diff --git a/src/main/javadoc/overview.html b/src/main/javadoc/overview.html
new file mode 100644
index 0000000000..0598cf19d0
--- /dev/null
+++ b/src/main/javadoc/overview.html
@@ -0,0 +1,375 @@
+
+
+
+Apache Commons CSV Overview
+
+
+
+
Custom formats can be created using a fluent style API.
+
+
+
Parsing Standard CSV Files
+
+ Parsing files with Apache Commons CSV is relatively straight forward. Pick a
+ CSVFormat
+ and go from there.
+
+
+
Parsing an Excel CSV File
+
To parse an Excel CSV file, write:
+
+
+Reader in = new FileReader("path/to/file.csv");
+Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
+for (CSVRecord record : records) {
+ String lastName = record.get("Last Name");
+ String firstName = record.get("First Name");
+}
+
+
+
+
+
+
Parsing Custom CSV Files
+
+ You can define your own using IO rules by building your own CSVFormat instance. Starting with
+ CSVFormat.builder()
+ lets you start from a predefined format and customize. For example:
+
+ To handle files that start with a Byte Order Mark (BOM), like some Excel CSV files, you need an extra step to deal with the optional BOM bytes. Using the
+ BOMInputStream class from Apache Commons IO simplifies this task; for example:
+
You might find it handy to create something like this:
+
+
+/**
+ * Creates a reader capable of handling BOMs.
+ *
+ * @param path The path to read.
+ * @return a new InputStreamReader for UTF-8 bytes.
+ * @throws IOException if an I/O error occurs.
+ */
+public InputStreamReader newReader(final Path path) throws IOException {
+ return new InputStreamReader(BOMInputStream.builder()
+ .setPath(path)
+ .get(), StandardCharsets.UTF_8);
+}
+
+
+
+
+
Using Headers
+
+ Apache Commons CSV provides several ways to access record values. The simplest way is to access values by their index in the record. However, columns in
+ CSV files often have a name, for example: ID, CustomerNo, Birthday, etc. The CSVFormat class provides an API for specifying these header names and
+ CSVRecord on the other hand has methods to access values by their corresponding header name.
+
+
+
Accessing column values by index
+
To access a record value by index, no special configuration of the CSVFormat is necessary:
+
+
+Reader in = new FileReader("path/to/file.csv");
+Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
+for (CSVRecord record : records) {
+ String columnOne = record.get(0);
+ String columnTwo = record.get(1);
+}
+
+
+
+
+
Defining a header manually
+
Indices may not be the most intuitive way to access record values. For this reason it is possible to assign names to each column in the file:
+
+
+Reader in = new FileReader("path/to/file.csv");
+Iterable<CSVRecord> records = CSVFormat.RFC4180.builder()
+ .setHeader("ID", "CustomerNo", "Name")
+ .build()
+ .parse(in);
+for (CSVRecord record : records) {
+ String id = record.get("ID");
+ String customerNo = record.get("CustomerNo");
+ String name = record.get("Name");
+}
+
+
+ Note that column values can still be accessed using their index.
+
+
+
Using an enum to define a header
+
Using String values all over the code to reference columns can be error prone. For this reason, it is possible to define an enum to specify header
+ names. Note that the enum constant names are used to access column values. This may lead to enums constant names which do not follow the Java coding
+ standard of defining constants in upper case with underscores:
+
+
+public enum Headers {
+ ID, CustomerNo, Name
+}
+Reader in = new FileReader("path/to/file.csv");
+Iterable<CSVRecord> records = CSVFormat.RFC4180.builder()
+ .setHeader(Headers.class)
+ .build()
+ .parse(in);
+for (CSVRecord record : records) {
+ String id = record.get(Headers.ID);
+ String customerNo = record.get(Headers.CustomerNo);
+ String name = record.get(Headers.Name);
+}
+
+
+ Again it is possible to access values by their index and by using a String (for example "CustomerNo").
+
+
+
Header auto detection
+
Some CSV files define header names in their first record. If configured, Apache Commons CSV can parse the header names from the first record:
+
+
+Reader in = new FileReader("path/to/file.csv");
+Iterable<CSVRecord> records = CSVFormat.RFC4180.builder()
+ .setHeader()
+ .setSkipHeaderRecord(true)
+ .build()
+ .parse(in);
+for (CSVRecord record : records) {
+ String id = record.get("ID");
+ String customerNo = record.get("CustomerNo");
+ String name = record.get("Name");
+}
+
+
+ This will use the values from the first record as header names and skip the first record when iterating.
+
+
+
+
Printing with headers
+
To print a CSV file with headers, you specify the headers in the format:
SQL lets you limit how many rows a SELECT statement returns with the LIMIT clause.
+
+ When you can't or don't want to change the SQL used to generate rows, JDBC lets you limit how many rows a JDBC Statement returns with the Statement.setMaxRows(int) method.
+
+
+ When you get a JDBC ResultSet from an API like
+ DatabaseMetaData.getProcedures(...), there is no SQL or JDBC Statement to use to set a limit, the ResultSet class does not have an API to limit rows.
+
+ Using the above, calling CSVPrinter.printRecords(ResultSet) will
+ limit the row count to the maximum number of rows specified in setMaxRows().
+
+
Note that setMaxRows() works with the other methods that print a sequence of records.
+
+
+
+
diff --git a/src/media/commons-logo-component-100.xcf b/src/media/commons-logo-component-100.xcf
new file mode 100644
index 0000000000..77d92f2779
Binary files /dev/null and b/src/media/commons-logo-component-100.xcf differ
diff --git a/src/media/commons-logo-component.xcf b/src/media/commons-logo-component.xcf
new file mode 100644
index 0000000000..3670221da7
Binary files /dev/null and b/src/media/commons-logo-component.xcf differ
diff --git a/src/media/logo.png b/src/media/logo.png
new file mode 100644
index 0000000000..93bb6c0148
Binary files /dev/null and b/src/media/logo.png differ
diff --git a/src/site/resources/images/logo.png b/src/site/resources/images/logo.png
index 77e721d2c7..93bb6c0148 100644
Binary files a/src/site/resources/images/logo.png and b/src/site/resources/images/logo.png differ
diff --git a/src/site/resources/images/logo.xcf b/src/site/resources/images/logo.xcf
deleted file mode 100644
index 98ff21ec1d..0000000000
Binary files a/src/site/resources/images/logo.xcf and /dev/null differ
diff --git a/src/site/resources/pmd/pmd-ruleset.xml b/src/site/resources/pmd/pmd-ruleset.xml
new file mode 100644
index 0000000000..74e41f991d
--- /dev/null
+++ b/src/site/resources/pmd/pmd-ruleset.xml
@@ -0,0 +1,76 @@
+
+
+
+
+ This ruleset checks the code for discouraged programming constructs.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/site/resources/profile.jacoco b/src/site/resources/profile.jacoco
index e69de29bb2..0314c63ff2 100644
--- a/src/site/resources/profile.jacoco
+++ b/src/site/resources/profile.jacoco
@@ -0,0 +1,16 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
diff --git a/src/site/resources/spotbugs/spotbugs-exclude-filter.xml b/src/site/resources/spotbugs/spotbugs-exclude-filter.xml
new file mode 100644
index 0000000000..79c57d3ae4
--- /dev/null
+++ b/src/site/resources/spotbugs/spotbugs-exclude-filter.xml
@@ -0,0 +1,65 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/site/site.xml b/src/site/site.xml
index d1cd7333d6..232c2056c5 100644
--- a/src/site/site.xml
+++ b/src/site/site.xml
@@ -7,7 +7,7 @@
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -15,48 +15,29 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
-
-
-
- Apache Commons CSV
- /images/logo.png
- /index.html
- Commons CSV™ logo
+
+
+
-
-
-
-
-
-
-
-
+
diff --git a/src/site/xdoc/download_csv.xml b/src/site/xdoc/download_csv.xml
index 4eaf01547e..151c3f69ec 100644
--- a/src/site/xdoc/download_csv.xml
+++ b/src/site/xdoc/download_csv.xml
@@ -7,7 +7,7 @@ The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -26,22 +26,24 @@ limitations under the License.
| commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+======================================================================+
| |
- | 1) Re-generate using: mvn commons:download-page |
+ | 1) Re-generate using: mvn commons-build:download-page |
| |
| 2) Set the following properties in the component's pom: |
- | - commons.componentid (required, alphabetic, lower case) |
+ | - commons.componentid (required, alphabetic, lower case) |
| - commons.release.version (required) |
| - commons.release.name (required) |
| - commons.binary.suffix (optional) |
| (defaults to "-bin", set to "" for pre-maven2 releases) |
| - commons.release.desc (optional) |
| - commons.release.subdir (optional) |
+ | - commons.release.hash (optional, lowercase, default sha512) |
| |
- | - commons.release.2/3.version (conditional) |
- | - commons.release.2/3.name (conditional) |
- | - commons.release.2/3.binary.suffix (optional) |
- | - commons.release.2/3.desc (optional) |
- | - commons.release.2/3.subdir (optional) |
+ | - commons.release.[234].version (conditional) |
+ | - commons.release.[234].name (conditional) |
+ | - commons.release.[234].binary.suffix (optional) |
+ | - commons.release.[234].desc (optional) |
+ | - commons.release.[234].subdir (optional) |
+ | - commons.release.[234].hash (optional, lowercase, [sha512])|
| |
| 3) Example Properties |
| (commons.release.name inherited by parent: |
@@ -54,17 +56,19 @@ limitations under the License.
| |
+======================================================================+
-->
-
+Download Apache Commons CSV
- Apache Commons Documentation Team
+ Apache Commons Team
We recommend you use a mirror to download our release
- builds, but you mustverify the integrity of
+ builds, but you mustverify the integrity of
the downloaded files using signatures downloaded from our main
distribution directories. Recent releases (48 hours) may not yet
be available from all the mirrors.
@@ -77,7 +81,7 @@ limitations under the License.
mirrors (at the end of the mirrors list) that should be
available.
- [if-any logo][end]
+ [if-any logo][end]
diff --git a/src/site/xdoc/index.xml b/src/site/xdoc/index.xml
index 8d8b2488a1..ac5b8cfa9f 100644
--- a/src/site/xdoc/index.xml
+++ b/src/site/xdoc/index.xml
@@ -7,7 +7,7 @@ The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -18,97 +18,84 @@ limitations under the License.
Home
- Commons Documentation Team
+ Apache Commons Team
+
+
+
-
Commons CSV reads and writes files in variations of the Comma Separated Value (CSV) format.
-
The most common CSV formats are predefined in the CSVFormat class:
-
The commons developer mailing list is the main channel of communication for contributors. Please remember that the lists are shared between all commons components, so prefix your email by [csv].
-
You can also visit the #apache-commons IRC channel on irc.freenode.net or peruse JIRA. Specific links of interest for JIRA are:
+
You can also peruse JIRA. Specific links of interest for JIRA are:
-
-
diff --git a/src/site/xdoc/issue-tracking.xml b/src/site/xdoc/issue-tracking.xml
index c15ab0e651..3aa64b4042 100644
--- a/src/site/xdoc/issue-tracking.xml
+++ b/src/site/xdoc/issue-tracking.xml
@@ -7,7 +7,7 @@ The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -26,7 +26,7 @@ limitations under the License.
| commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+======================================================================+
| |
- | 1) Re-generate using: mvn commons:jira-page |
+ | 1) Re-generate using: mvn commons-build:jira-page |
| |
| 2) Set the following properties in the component's pom: |
| - commons.jira.id (required, alphabetic, upper case) |
@@ -41,10 +41,12 @@ limitations under the License.
| |
+======================================================================+
-->
-
+Apache Commons CSV Issue tracking
- Apache Commons Documentation Team
+ Apache Commons Team
@@ -64,6 +66,7 @@ limitations under the License.
If you would like to report a bug, or raise an enhancement request with
Apache Commons CSV please do the following:
+
Search existing open bugs.
If you find your issue listed then please add a comment with your details.
@@ -73,30 +76,29 @@ limitations under the License.
-
diff --git a/src/site/xdoc/mail-lists.xml b/src/site/xdoc/mail-lists.xml
index 8eb001ef51..345cef8996 100644
--- a/src/site/xdoc/mail-lists.xml
+++ b/src/site/xdoc/mail-lists.xml
@@ -7,7 +7,7 @@ The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -26,7 +26,7 @@ limitations under the License.
| commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+======================================================================+
| |
- | 1) Re-generate using: mvn commons:mail-page |
+ | 1) Re-generate using: mvn commons-build:mail-page |
| |
| 2) Set the following properties in the component's pom: |
| - commons.componentid (required, alphabetic, lower case) |
@@ -39,29 +39,31 @@ limitations under the License.
| |
+======================================================================+
-->
-
+Apache Commons CSV Mailing Lists
- Apache Commons Documentation Team
+ Apache Commons Team
Apache Commons CSV shares mailing lists with all the other
- Commons Components.
+ Commons Components.
To make it easier for people to only read messages related to components they are interested in,
the convention in Commons is to prefix the subject line of messages with the component's name,
for example:
-
-
[csv] Problem with the ...
-
+
+
[csv] Problem with the ...
+
Questions related to the usage of Apache Commons CSV should be posted to the
- User List.
+ User List.
- The Developer List
+ The Developer List
is for questions and discussion related to the development of Apache Commons CSV.
Please do not cross-post; developers are also subscribed to the user list.
@@ -70,8 +72,10 @@ limitations under the License.
to subscribe.
- Note: please don't send patches or attachments to any of the mailing lists.
+ Note: please don't send patches or attachments to any of the mailing lists;
+ most of the lists are set up to drop attachments.
Patches are best handled via the Issue Tracking system.
+ If you have a GitHub account, most components also accept PRs (pull requests).
Otherwise, please upload the file to a public server and include the URL in the mail.
@@ -105,10 +109,11 @@ limitations under the License.
+ For information about reporting or asking questions about security, please see
+ Apache Commons Security.
+
+
This page lists all security vulnerabilities fixed in released versions of this component.
+
+
Please note that binary patches are never provided. If you need to apply a source code patch, use the building instructions for the component version
+ that you are using.
+
+
+ If you need help on building this component or other help on following the instructions to mitigate the known vulnerabilities listed here, please send
+ your questions to the public
+ user mailing list.
+
+
If you have encountered an unlisted security vulnerability or other unexpected behavior that has security impact, or if the descriptions here are
+ incomplete, please report them privately to the Apache Security Team. Thank you.
+
+
+
+
None.
+
+
+
+ For information about safe deserialization, please see Safe Deserialization.
+
+
+
+
\ No newline at end of file
diff --git a/src/site/xdoc/user-guide.xml b/src/site/xdoc/user-guide.xml
index f3801a616d..d5a1f26850 100644
--- a/src/site/xdoc/user-guide.xml
+++ b/src/site/xdoc/user-guide.xml
@@ -7,7 +7,7 @@ The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,156 +21,6 @@ limitations under the License.
Apache Commons Documentation Team
-
-
-
Apache Commons CSV User Guide
-
-
-
-
-
-
- Parsing files with Apache Commons CSV is relatively straight forward.
- The CSVFormat class provides some commonly used CSV variants:
-
-
- Reader in = new FileReader("path/to/file.csv");
-Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
-for (CSVRecord record : records) {
- String lastName = record.get("Last Name");
- String firstName = record.get("First Name");
-}
-
-
-
-
- To handle files that start with a Byte Order Mark (BOM) like some Excel CSV files, you need an extra step to
- deal with these optional bytes.
- You can use the
-
- BOMInputStream
-
- class from
- Apache Commons IO
- for example:
-
- final URL url = ...;
-final Reader reader = new InputStreamReader(new BOMInputStream(url.openStream()), "UTF-8");
-final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
-try {
- for (final CSVRecord record : parser) {
- final String string = record.get("SomeColumn");
- ...
- }
-} finally {
- parser.close();
- reader.close();
-}
-
-
- You might find it handy to create something like this:
-
- /**
-* Creates a reader capable of handling BOMs.
-*/
-public InputStreamReader newReader(final InputStream inputStream) {
- return new InputStreamReader(new BOMInputStream(inputStream), StandardCharsets.UTF_8);
-}
-
-
-
-
-
-
- Apache Commons CSV provides several ways to access record values.
- The simplest way is to access values by their index in the record.
- However, columns in CSV files often have a name, for example: ID, CustomerNo, Birthday, etc.
- The CSVFormat class provides an API for specifing these header names and CSVRecord on
- the other hand has methods to access values by their corresponding header name.
-
-
- To access a record value by index, no special configuration of the CSVFormat is necessary:
- Reader in = new FileReader("path/to/file.csv");
-Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
-for (CSVRecord record : records) {
- String columnOne = record.get(0);
- String columnTwo = record.get(1);
-}
-
-
-
- Indices may not be the most intuitive way to access record values. For this reason it is possible to
- assign names to each column in the file:
- Reader in = new FileReader("path/to/file.csv");
-Iterable<CSVRecord> records = CSVFormat.RFC4180.withHeader("ID", "CustomerNo", "Name").parse(in);
-for (CSVRecord record : records) {
- String id = record.get("ID");
- String customerNo = record.get("CustomerNo");
- String name = record.get("Name");
-}
-
- Note that column values can still be accessed using their index.
-
-
- Using String values all over the code to reference columns can be error prone. For this reason,
- it is possible to define an enum to specify header names. Note that the enum constant names are
- used to access column values. This may lead to enums constant names which do not follow the Java
- coding standard of defining constants in upper case with underscores:
- public enum Headers {
- ID, CustomerNo, Name
-}
-Reader in = new FileReader("path/to/file.csv");
-Iterable<CSVRecord> records = CSVFormat.RFC4180.withHeader(Headers.class).parse(in);
-for (CSVRecord record : records) {
- String id = record.get(Headers.ID);
- String customerNo = record.get(Headers.CustomerNo);
- String name = record.get(Headers.Name);
-}
-
- Again it is possible to access values by their index and by using a String (for example "CustomerNo").
-
-
- Some CSV files define header names in their first record. If configured, Apache Commons CSV can parse
- the header names from the first record:
- Reader in = new FileReader("path/to/file.csv");
-Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
-for (CSVRecord record : records) {
- String id = record.get("ID");
- String customerNo = record.get("CustomerNo");
- String name = record.get("Name");
-}
-
- This will use the values from the first record as header names and skip the first record when iterating.
-
-
-
- To print a CSV file with headers, you specify the headers in the format:
-
- final Appendable out = ...;
- final CSVPrinter printer = CSVFormat.DEFAULT.withHeader("H1", "H2").print(out)
-
-
- To print a CSV file with JDBC column labels, you specify the ResultSet in the format:
-
- final ResultSet resultSet = ...;
- final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(out)
-
-
-
-
+
diff --git a/src/test/java/org/apache/commons/csv/AssertionsTest.java b/src/test/java/org/apache/commons/csv/AssertionsTest.java
deleted file mode 100644
index af41275d99..0000000000
--- a/src/test/java/org/apache/commons/csv/AssertionsTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.commons.csv;
-
-import org.junit.Test;
-
-/**
- */
-public class AssertionsTest {
-
- @Test
- public void testNotNull() throws Exception {
- Assertions.notNull(new Object(), "object");
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testNotNullNull() throws Exception {
- Assertions.notNull(null, "object");
- }
-}
diff --git a/src/test/java/org/apache/commons/csv/CSVBenchmark.java b/src/test/java/org/apache/commons/csv/CSVBenchmark.java
index b2ecd52842..b1be4ce095 100644
--- a/src/test/java/org/apache/commons/csv/CSVBenchmark.java
+++ b/src/test/java/org/apache/commons/csv/CSVBenchmark.java
@@ -1,33 +1,35 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * https://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.commons.csv;
import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.Reader;
import java.io.StringReader;
-import java.util.List;
+import java.nio.charset.StandardCharsets;
+import java.util.Iterator;
+import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
-import com.generationjava.io.CsvReader;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.openjdk.jmh.annotations.Benchmark;
@@ -45,6 +47,10 @@
import org.supercsv.io.CsvListReader;
import org.supercsv.prefs.CsvPreference;
+import com.generationjava.io.CsvReader;
+import com.opencsv.CSVParserBuilder;
+import com.opencsv.CSVReaderBuilder;
+
@BenchmarkMode(Mode.AverageTime)
@Fork(value = 1, jvmArgs = {"-server", "-Xms1024M", "-Xmx1024M"})
@Threads(1)
@@ -54,157 +60,169 @@
@State(Scope.Benchmark)
public class CSVBenchmark {
+ private static final class CountingReaderCallback implements org.skife.csv.ReaderCallback {
+ public int count;
+
+ @Override
+ public void onRow(final String[] fields) {
+ count++;
+ }
+ }
+
private String data;
+ private Reader getReader() {
+ return new StringReader(data);
+ }
+
/**
* Load the data in memory before running the benchmarks, this takes out IO from the results.
*/
@Setup
public void init() throws IOException {
- final File file = new File("src/test/resources/perf/worldcitiespop.txt.gz");
- final InputStream in = new GZIPInputStream(new FileInputStream(file));
- this.data = IOUtils.toString(in, "ISO-8859-1");
- in.close();
- }
-
- private BufferedReader getReader() throws IOException {
- return new BufferedReader(new StringReader(data));
- }
-
- @Benchmark
- public int read(final Blackhole bh) throws Exception {
- final BufferedReader in = getReader();
- int count = 0;
- String line;
- while ((line = in.readLine()) != null) {
- count++;
+ try (InputStream in = this.getClass().getClassLoader().getResourceAsStream("org/apache/commons/csv/perf/worldcitiespop.txt.gz");
+ InputStream gzin = new GZIPInputStream(in, 8192)) {
+ this.data = IOUtils.toString(gzin, StandardCharsets.ISO_8859_1);
}
-
- bh.consume(count);
- in.close();
- return count;
- }
-
- @Benchmark
- public int split(final Blackhole bh) throws Exception {
- final BufferedReader in = getReader();
- int count = 0;
- String line;
- while ((line = in.readLine()) != null) {
- final String[] values = StringUtils.split(line, ',');
- count += values.length;
- }
-
- bh.consume(count);
- in.close();
- return count;
}
@Benchmark
public int parseCommonsCSV(final Blackhole bh) throws Exception {
- final BufferedReader in = getReader();
-
- final CSVFormat format = CSVFormat.DEFAULT.withHeader();
-
int count = 0;
- for (final CSVRecord record : format.parse(in)) {
- count++;
+
+ try (Reader in = getReader()) {
+ final CSVFormat format = CSVFormat.Builder.create().setSkipHeaderRecord(true).build();
+ final Iterator iter = format.parse(in).iterator();
+ while (iter.hasNext()) {
+ count++;
+ iter.next();
+ }
}
bh.consume(count);
- in.close();
return count;
}
@Benchmark
public int parseGenJavaCSV(final Blackhole bh) throws Exception {
- final BufferedReader in = getReader();
-
- final CsvReader reader = new CsvReader(in);
- reader.setFieldDelimiter(',');
-
int count = 0;
- String[] record = null;
- while ((record = reader.readLine()) != null) {
- count++;
+
+ try (Reader in = getReader()) {
+ final CsvReader reader = new CsvReader(in);
+ reader.setFieldDelimiter(',');
+ while (reader.readLine() != null) {
+ count++;
+ }
}
bh.consume(count);
- in.close();
return count;
}
@Benchmark
public int parseJavaCSV(final Blackhole bh) throws Exception {
- final BufferedReader in = getReader();
-
- final com.csvreader.CsvReader reader = new com.csvreader.CsvReader(in, ',');
- reader.setRecordDelimiter('\n');
-
int count = 0;
- while (reader.readRecord()) {
- count++;
+
+ try (Reader in = getReader()) {
+ final com.csvreader.CsvReader reader = new com.csvreader.CsvReader(in, ',');
+ reader.setRecordDelimiter('\n');
+ while (reader.readRecord()) {
+ count++;
+ }
}
bh.consume(count);
- in.close();
return count;
}
@Benchmark
public int parseOpenCSV(final Blackhole bh) throws Exception {
- final BufferedReader in = getReader();
-
- final com.opencsv.CSVReader reader = new com.opencsv.CSVReader(in, ',');
-
int count = 0;
- while (reader.readNext() != null) {
- count++;
+
+ final com.opencsv.CSVParser parser = new CSVParserBuilder()
+ .withSeparator(',').withIgnoreQuotations(true).build();
+
+ try (Reader in = getReader()) {
+ final com.opencsv.CSVReader reader = new CSVReaderBuilder(in).withSkipLines(1).withCSVParser(parser).build();
+ while (reader.readNext() != null) {
+ count++;
+ }
}
bh.consume(count);
- in.close();
return count;
}
@Benchmark
public int parseSkifeCSV(final Blackhole bh) throws Exception {
- final BufferedReader in = getReader();
-
final org.skife.csv.CSVReader reader = new org.skife.csv.SimpleReader();
reader.setSeperator(',');
-
final CountingReaderCallback callback = new CountingReaderCallback();
- reader.parse(in, callback);
+
+ try (Reader in = getReader()) {
+ reader.parse(in, callback);
+ }
bh.consume(callback);
- in.close();
return callback.count;
}
- private static class CountingReaderCallback implements org.skife.csv.ReaderCallback {
- public int count = 0;
+ @Benchmark
+ public int parseSuperCSV(final Blackhole bh) throws Exception {
+ int count = 0;
- @Override
- public void onRow(final String[] fields) {
- count++;
+ try (CsvListReader reader = new CsvListReader(getReader(), CsvPreference.STANDARD_PREFERENCE)) {
+ while (reader.read() != null) {
+ count++;
+ }
}
+
+ bh.consume(count);
+ return count;
}
@Benchmark
- public int parseSuperCSV(final Blackhole bh) throws Exception {
- final BufferedReader in = getReader();
-
- final CsvListReader reader = new CsvListReader(in, CsvPreference.STANDARD_PREFERENCE);
+ public int read(final Blackhole bh) throws Exception {
+ int count = 0;
+
+ try (BufferedReader reader = new BufferedReader(getReader())) {
+ while (reader.readLine() != null) {
+ count++;
+ }
+ }
+
+ bh.consume(count);
+ return count;
+ }
+ @Benchmark
+ public int scan(final Blackhole bh) throws Exception {
int count = 0;
- List record = null;
- while ((record = reader.read()) != null) {
- count++;
+
+ try (Scanner scanner = new Scanner(getReader())) {
+ while (scanner.hasNextLine()) {
+ scanner.nextLine();
+ count++;
+ }
}
bh.consume(count);
- in.close();
return count;
}
+
+ @Benchmark
+ public int split(final Blackhole bh) throws Exception {
+ int count = 0;
+
+ try (BufferedReader reader = new BufferedReader(getReader())) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ final String[] values = StringUtils.split(line, ',');
+ count += values.length;
+ }
+ }
+
+ bh.consume(count);
+ return count;
+ }
}
diff --git a/src/test/java/org/apache/commons/csv/CSVDuplicateHeaderTest.java b/src/test/java/org/apache/commons/csv/CSVDuplicateHeaderTest.java
new file mode 100644
index 0000000000..2f518a1206
--- /dev/null
+++ b/src/test/java/org/apache/commons/csv/CSVDuplicateHeaderTest.java
@@ -0,0 +1,339 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.commons.csv;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Tests parsing of duplicate column names in a CSV header.
+ * The test verifies that headers are consistently handled by CSVFormat and CSVParser.
+ */
+class CSVDuplicateHeaderTest {
+
+ /**
+ * Return test cases for duplicate header data for use in CSVFormat.
+ *
+ * This filters the parsing test data to all cases where the allow missing column
+ * names flag is true and ignore header case is false: these flags are exclusively for parsing.
+ * CSVFormat validation applies to both parsing and writing and thus validation
+ * is less strict and behaves as if the allow missing column names constraint and
+ * the ignore header case behavior are absent.
+ * The filtered data is then returned with the parser flags set to both true and false
+ * for each test case.
+ *
+ *
+ * @return the stream of arguments
+ */
+ static Stream duplicateHeaderAllowsMissingColumnsNamesData() {
+ return duplicateHeaderData()
+ .filter(arg -> Boolean.TRUE.equals(arg.get()[1]) && Boolean.FALSE.equals(arg.get()[2]))
+ .flatMap(arg -> {
+ // Return test case with flags as all true/false combinations
+ final Object[][] data = new Object[4][];
+ final Boolean[] flags = {Boolean.TRUE, Boolean.FALSE};
+ int i = 0;
+ for (final Boolean a : flags) {
+ for (final Boolean b : flags) {
+ data[i] = arg.get().clone();
+ data[i][1] = a;
+ data[i][2] = b;
+ i++;
+ }
+ }
+ return Arrays.stream(data).map(Arguments::of);
+ });
+ }
+
+ /**
+ * Return test cases for duplicate header data for use in parsing (CSVParser). Uses the order:
+ *