diff --git a/.asf.yaml b/.asf.yaml
index 5ea25ac8897..33a8dd8c4ff 100644
--- a/.asf.yaml
+++ b/.asf.yaml
@@ -23,7 +23,8 @@ notifications:
pullrequests: issues@commons.apache.org
jira_options: link label
jobs: notifications@commons.apache.org
- issues_bot_dependabot: notifications@commons.apache.org
- pullrequests_bot_dependabot: 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/.github/dependabot.yml b/.github/dependabot.yml
index 00079caf1bc..90ec55f742e 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -18,10 +18,8 @@ updates:
- package-ecosystem: "maven"
directory: "/"
schedule:
- interval: "weekly"
- day: "friday"
+ interval: "quarterly"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
- interval: "weekly"
- day: "friday"
+ interval: "quarterly"
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 7578b4da036..9ff35c83e79 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -23,8 +23,8 @@ 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.
+- [ ] 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 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
index fcc16fe390a..cd7608df029 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -42,6 +42,7 @@ jobs:
security-events: write
strategy:
+ max-parallel: 20
fail-fast: false
matrix:
language: [ 'java' ]
@@ -50,10 +51,10 @@ jobs:
steps:
- name: Checkout repository
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
+ - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 #v6.1.0
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
@@ -62,7 +63,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
- uses: github/codeql-action/init@303c0aef88fc2fe5ff6d63d3b1596bfd83dfa1f9 # 3.29.5
+ uses: github/codeql-action/init@99df26d4f13ea111d4ec1a7dddef6063f76b97e9 # v4.37.0
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -73,7 +74,7 @@ jobs:
# 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@303c0aef88fc2fe5ff6d63d3b1596bfd83dfa1f9 # 3.29.5
+ uses: github/codeql-action/autobuild@99df26d4f13ea111d4ec1a7dddef6063f76b97e9 # v4.37.0
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -87,4 +88,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@303c0aef88fc2fe5ff6d63d3b1596bfd83dfa1f9 # 3.29.5
+ uses: github/codeql-action/analyze@99df26d4f13ea111d4ec1a7dddef6063f76b97e9 # v4.37.0
diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml
index 1e043924237..7bc02bdd23d 100644
--- a/.github/workflows/dependency-review.yml
+++ b/.github/workflows/dependency-review.yml
@@ -26,6 +26,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: 'Checkout Repository'
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- name: 'Dependency Review PR'
- uses: actions/dependency-review-action@595b5aeba73380359d98a5e087f648dbb0edce1b # v4.7.3
+ uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml
index 7d0f0892434..a5d45fbb1e6 100644
--- a/.github/workflows/maven.yml
+++ b/.github/workflows/maven.yml
@@ -37,9 +37,10 @@ jobs:
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.experimental }}
strategy:
+ max-parallel: 20
matrix:
- os: [ubuntu-latest, windows-latest, macos-13]
- java: [ 8, 11, 17, 21 ]
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ java: [ 8, 11, 17, 21, 25, 26 ]
experimental: [false]
# Keep the same parameter order as the matrix above
include:
@@ -48,41 +49,31 @@ jobs:
java: 21
experimental: false
deploy: true
- # Experimental builds: Java 25-ea
+ # Experimental builds: Java 27-ea
- os: ubuntu-latest
- java: 25
+ java: 27-ea
experimental: true
- os: windows-latest
- java: 25
+ java: 27-ea
experimental: true
- os: macos-latest
- java: 25
- experimental: true
- # Experimental builds: Java 26-ea
- - os: ubuntu-latest
- java: 26-ea
- experimental: true
- - os: windows-latest
- java: 26-ea
- experimental: true
- - os: macos-latest
- java: 26-ea
+ java: 27-ea
experimental: true
fail-fast: false
steps:
- - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
+ - 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@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
+ uses: actions/setup-java@0f481fcb613427c0f801b606911222b5b6f3083a # 5.5.0
with:
- distribution: 'temurin'
+ distribution: ${{ runner.os == 'macOS' && matrix.java == '8' && 'zulu' || 'temurin' }}
java-version: ${{ matrix.java }}
# these values cause the plugin to set up the Maven settings.xml file
server-id: apache.snapshots.https # Value of the distributionManagement/repository/id field of the pom.xml
diff --git a/.github/workflows/scorecards-analysis.yml b/.github/workflows/scorecards-analysis.yml
index cf4d6ba87b0..4587c940d79 100644
--- a/.github/workflows/scorecards-analysis.yml
+++ b/.github/workflows/scorecards-analysis.yml
@@ -42,12 +42,12 @@ jobs:
steps:
- name: "Checkout code"
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
- name: "Run analysis"
- uses: ossf/scorecard-action@05b42c624433fc40578a4040d5cf5e36ddca8cde # 2.4.2
+ uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # 2.4.3
with:
results_file: results.sarif
results_format: sarif
@@ -59,13 +59,13 @@ jobs:
publish_results: true
- name: "Upload artifact"
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # 4.6.2
+ 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@303c0aef88fc2fe5ff6d63d3b1596bfd83dfa1f9 # 3.29.5
+ uses: github/codeql-action/upload-sarif@99df26d4f13ea111d4ec1a7dddef6063f76b97e9 # v4.37.0
with:
sarif_file: results.sarif
diff --git a/.gitignore b/.gitignore
index f43fea02686..91824e5be73 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,3 @@
-### https://raw.github.com/github/gitignore/14b7566ce157ce95b07006466bacee160f242284/maven.gitignore
-
target/
pom.xml.tag
pom.xml.releaseBackup
@@ -7,16 +5,19 @@ pom.xml.versionsBackup
pom.xml.next
release.properties
-
site-content
/.classpath
/.project
/.settings/
-### Ignore IntelliJ files
+# Ignore IntelliJ files
/.idea/
*.iml
/bin/
-### Ignore Visual Studio code files
+# Ignore Visual Studio code files
/.vscode/
+
+# NetBeans files
+nb-configuration.xml
+nbactions.xml
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f708680735d..babb08bb394 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -48,13 +48,13 @@ 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). This is not essential, but makes providing patches much easier.
++ 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 IO'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. If you don't have a GitHub account, you can still clone the Commons 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
--------------
@@ -69,7 +69,7 @@ Making Changes
+ Respect the original code style:
+ 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.
-+ 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.
++ 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.
@@ -108,9 +108,8 @@ Additional Resources
+ [Contributing patches](https://commons.apache.org/patches.html)
+ [Apache Commons IO 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/)
-+ [Apache Commons Twitter Account](https://twitter.com/ApacheCommons)
++ [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)
[cla]:https://www.apache.org/licenses/#clas
[jira]:https://issues.apache.org/jira/browse/IO
diff --git a/NOTICE.txt b/NOTICE.txt
index 2a4682551b1..b9fb860712d 100644
--- a/NOTICE.txt
+++ b/NOTICE.txt
@@ -1,5 +1,5 @@
Apache Commons IO
-Copyright 2002-2025 The Apache Software Foundation
+Copyright 2002-2026 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (https://www.apache.org/).
diff --git a/README.md b/README.md
index bb31ce854a6..8e4ae6db426 100644
--- a/README.md
+++ b/README.md
@@ -45,7 +45,7 @@ Apache Commons IO
[](https://github.com/apache/commons-io/actions/workflows/maven.yml)
[](https://search.maven.org/artifact/commons-io/commons-io)
-[](https://javadoc.io/doc/commons-io/commons-io/2.20.0)
+[](https://javadoc.io/doc/commons-io/commons-io/2.22.0)
[](https://github.com/apache/commons-io/actions/workflows/codeql-analysis.yml)
[](https://api.securityscorecards.dev/projects/github.com/apache/commons-io)
@@ -69,7 +69,7 @@ Alternatively, you can pull it from the central Maven repositories:
commons-iocommons-io
- 2.20.0
+ 2.22.0
```
@@ -90,7 +90,7 @@ There are some guidelines which will make applying PRs easier for us:
+ 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`.
-+ Before you pushing a PR, run `mvn` (by itself), this runs the default goal, which contains all build checks.
++ Before you push a PR, run `mvn` (without arguments). 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).
@@ -112,7 +112,6 @@ Additional Resources
+ [Apache Commons Homepage](https://commons.apache.org/)
+ [Apache Issue Tracker (JIRA)](https://issues.apache.org/jira/browse/IO)
+ [Apache Commons Slack Channel](https://the-asf.slack.com/archives/C60NVB8AD)
-+ [Apache Commons Twitter Account](https://twitter.com/ApacheCommons)
Apache Commons Components
-------------------------
diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt
index 1f30f8b0f5a..904a8f55302 100644
--- a/RELEASE-NOTES.txt
+++ b/RELEASE-NOTES.txt
@@ -1,5 +1,281 @@
+Apache Commons IO 2.22.0 Release Notes
+--------------------------------------
+
+The Apache Commons IO team is pleased to announce the release of Apache Commons IO 2.22.0.
+
+Introduction
+------------
+
+The Apache Commons IO library contains utility classes, stream implementations, file filters,
+file comparators, endian transformation classes, and much more.
+
+This is a feature and maintenance release. Java 8 or later is required.
+
+New features
+------------
+
+o Add and use IOUtils.closeQuietlySuppress(Closeable, Throwable) #818. Thanks to Gary Gregory, Piotr P. Karwasz.
+o Add ProxyWriter.setReference(Writer). Thanks to Gary Gregory.
+o Add ProxyWriter.unwrap(). Thanks to Gary Gregory.
+o Add ProxyReader.setReference(Reader). Thanks to Gary Gregory.
+o Add ProxyReader.unrwap(). Thanks to Gary Gregory.
+o IO-883: ByteArraySeekableByteChannel should optionally configure a read-only channel. Thanks to Konrad Windszus, Gary Gregory, Makarand Hinge.
+o IO-883: Add ByteArraySeekableByteChannel.Builder and builder(). Thanks to Gary Gregory.
+o IO-883: Add AbstractStreamBuilder.getByteArray(). Thanks to Gary Gregory.
+o CloseShieldInputStream now supports a custom close shield as a function #836. Thanks to Gary Gregory.
+o Add FlushShieldOutputStream to workaround issues in generic code that ends up calling third parties like like org.tukaani.xz.LZMAOutputStream.flush(). Thanks to Gary Gregory.
+o Add filter channels. Thanks to Gary Gregory.
+
+Fixed Bugs
+----------
+
+o Fix Apache RAT plugin console warnings. Thanks to Gary Gregory.
+o ByteArraySeekableByteChannel.position(long) and truncate(long) shouldn't throw an IllegalArgumentException for a new positive position that's too large #817. Thanks to Gary Gregory, Piotr P. Karwasz.
+o Fix malformed Javadoc comments. Thanks to Gary Gregory.
+o ReadAheadInputStream.close() doesn't always close its filtered input stream. Thanks to Stanislav Fort, Gary Gregory.
+o ReadAheadInputStream now restores the current thread's interrupt flag when catching InterruptedException. Thanks to Gary Gregory.
+o FileAlterationMonitor.stop(long) now restores the current thread's interrupt flag when catching InterruptedException. Thanks to Gary Gregory.
+o FileCleaningTracker now restores the current thread's interrupt flag when catching InterruptedException. Thanks to Gary Gregory.
+o ThreadMonitor.run() now restores the current thread's interrupt flag when catching InterruptedException. Thanks to Gary Gregory.
+o ThrottledInputStream.throttle() now restores the current thread's interrupt flag when catching InterruptedException. Thanks to Gary Gregory.
+o ThrottledInputStream.throttle() doesn't preserve the original InterruptedException as the cause of its InterruptedIOException. Thanks to Gary Gregory.
+o All thread names are now prefixed with "commons-io-". Thanks to Gary Gregory.
+o IO-639: ReversedLinesFileReader does not read first line if its empty #829. Thanks to Kishor, Mashrur Mia.
+o IO-886: Fixed incorrect regular expression in PathUtils.RelativeSortedPaths.extractKey(String, String). Thanks to Peter De Maeyer.
+o Fix typos in Javadoc of FileUtils and related test classes #833. Thanks to Martin Wiesner.
+o IO-887: WriterOutputStream from a builder fails on malformed or unmappable input bytes. Thanks to Daniel Vega, Gary Gregory.
+o BoundedReader now extends ProxyReader. Thanks to Gary Gregory.
+o AbstractStreamBuilder.setOpenOptions(OpenOption...) now makes a defensive copy of its input array. Thanks to Gary Gregory.
+o IO-885: Path visits follow links #832. Thanks to Peter De Maeyer, Gary Gregory.
+o BOMInputStream fail-fast and tracks its ByteOrderMark as a final #835. Thanks to Gary Gregory.
+o Refactor UnixLineEndingInputStream and WindowsLineEndingInputStream for duplication. Thanks to Gary Gregory.
+o IO-857: [Javadoc] PathUtils.cleanDirectory() methods vs FileUtils. Thanks to Peter De Maeyer, Gary Gregory.
+o Fix JaCoCo report generation (code coverage). Thanks to Gary Gregory.
+o AbstractStreamBuilder.setBufferSizeDefault(int) now resets to default for input less than or equal to zero. Thanks to Gary Gregory.
+
+Changes
+-------
+
+o Bump org.apache.commons:commons-parent from 91 to 98 #816. Thanks to Gary Gregory, Dependabot.
+o Bump commons-codec:commons-codec from 1.19.0 to 1.21.0 #812. Thanks to Gary Gregory, Dependabot.
+o Bump commons.bytebuddy.version from 1.17.8 to 1.18.8 #814, #820, #838. Thanks to Gary Gregory, Dependabot.
+o Bump commons-lang3 from 3.19.0 to 3.20.0. Thanks to Gary Gregory, Dependabot.
+
+
+Commons IO 2.7 and up requires Java 8 or above.
+Commons IO 2.6 requires Java 7 or above.
+Commons IO 2.3 through 2.5 requires Java 6 or above.
+Commons IO 2.2 requires Java 5 or above.
+Commons IO 1.4 requires Java 1.3 or above.
+
+Historical list of changes: https://commons.apache.org/proper/commons-io/changes.html
+
+For complete information on Apache Commons IO, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons IO website:
+
+https://commons.apache.org/proper/commons-io/
+
+Download page: https://commons.apache.org/proper/commons-io/download_io.cgi
+
+Have fun!
+-Apache Commons Team
+
+------------------------------------------------------------------------------
+
+
+Apache Commons IO 2.22.0 Release Notes
+--------------------------------------
+
+The Apache Commons IO team is pleased to announce the release of Apache Commons IO 2.22.0.
+
+Introduction
+------------
+
+The Apache Commons IO library contains utility classes, stream implementations, file filters,
+file comparators, endian transformation classes, and much more.
+
+This is a feature and maintenance release. Java 8 or later is required.
+
+New features
+------------
+
+o Add and use IOUtils.closeQuietlySuppress(Closeable, Throwable) #818. Thanks to Gary Gregory, Piotr P. Karwasz.
+
+Fixed Bugs
+----------
+
+o Fix Apache RAT plugin console warnings. Thanks to Gary Gregory.
+o ByteArraySeekableByteChannel.position(long) and truncate(long) shouldn't throw an IllegalArgumentException for a new positive position that's too large #817. Thanks to Gary Gregory, Piotr P. Karwasz.
+o Fix malformed Javadoc comments. Thanks to Gary Gregory.
+o ReadAheadInputStream.close() doesn't always close its filtered input stream. Thanks to Stanislav Fort, Gary Gregory.
+
+Changes
+-------
+
+o Bump org.apache.commons:commons-parent from 91 to 96 #816. Thanks to Gary Gregory, Dependabot.
+o Bump commons-codec:commons-codec from 1.19.0 to 1.20.0 #812. Thanks to Gary Gregory, Dependabot.
+o Bump commons.bytebuddy.version from 1.17.8 to 1.18.4 #814, #820. Thanks to Gary Gregory, Dependabot.
+o Bump commons-lang3 from 3.19.0 to 3.20.0. Thanks to Gary Gregory, Dependabot.
+
+
+Commons IO 2.7 and up requires Java 8 or above.
+Commons IO 2.6 requires Java 7 or above.
+Commons IO 2.3 through 2.5 requires Java 6 or above.
+Commons IO 2.2 requires Java 5 or above.
+Commons IO 1.4 requires Java 1.3 or above.
+
+Historical list of changes: https://commons.apache.org/proper/commons-io/changes.html
+
+For complete information on Apache Commons IO, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons IO website:
+
+https://commons.apache.org/proper/commons-io/
+
+Download page: https://commons.apache.org/proper/commons-io/download_io.cgi
+
+Have fun!
+-Apache Commons Team
+
+------------------------------------------------------------------------------
+
+Apache Commons IO 2.22.0 Release Notes
+--------------------------------------
+
+The Apache Commons IO team is pleased to announce the release of Apache Commons IO 2.22.0.
+
+Introduction
+------------
+
+The Apache Commons IO library contains utility classes, stream implementations, file filters,
+file comparators, endian transformation classes, and much more.
+
+This is a feature and maintenance release. Java 8 or later is required.
+
+New features
+------------
+
+o Add and use IOUtils.closeQuietly(Closeable, Throwable) #818. Thanks to Gary Gregory.
+
+Fixed Bugs
+----------
+
+o Fix Apache RAT plugin console warnings. Thanks to Gary Gregory.
+o ByteArraySeekableByteChannel.position(long) and truncate(long) shouldn't throw an IllegalArgumentException for a new positive position that's too large #817. Thanks to Gary Gregory, Piotr P. Karwasz.
+o Fix malformed Javadoc comments. Thanks to Gary Gregory.
+o ReadAheadInputStream.close() doesn't always close its filtered input stream. Thanks to Stanislav Fort, Gary Gregory.
+
+Changes
+-------
+
+o Bump org.apache.commons:commons-parent from 91 to 95 #816. Thanks to Gary Gregory, Dependabot.
+o Bump commons-codec:commons-codec from 1.19.0 to 1.20.0 #812. Thanks to Gary Gregory, Dependabot.
+o Bump commons.bytebuddy.version from 1.17.8 to 1.18.3 #814, #820. Thanks to Gary Gregory, Dependabot.
+o Bump commons-lang3 from 3.19.0 to 3.20.0. Thanks to Gary Gregory, Dependabot.
+
+
+Commons IO 2.7 and up requires Java 8 or above.
+Commons IO 2.6 requires Java 7 or above.
+Commons IO 2.3 through 2.5 requires Java 6 or above.
+Commons IO 2.2 requires Java 5 or above.
+Commons IO 1.4 requires Java 1.3 or above.
+
+Historical list of changes: https://commons.apache.org/proper/commons-io/changes.html
+
+For complete information on Apache Commons IO, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons IO website:
+
+https://commons.apache.org/proper/commons-io/
+
+Download page: https://commons.apache.org/proper/commons-io/download_io.cgi
+
+Have fun!
+-Apache Commons Team
+
+------------------------------------------------------------------------------
+
+
+Apache Commons IO 2.21.0 Release Notes
+--------------------------------------
+
+The Apache Commons IO team is pleased to announce the release of Apache Commons IO 2.21.0.
+
+Introduction
+------------
+
+The Apache Commons IO library contains utility classes, stream implementations, file filters,
+file comparators, endian transformation classes, and much more.
+
+Version 2.21.0: Java 8 or later is required.
+
+New features
+------------
+
+o FileUtils#byteCountToDisplaySize() supports Zettabyte, Yottabyte, Ronnabyte and Quettabyte #763. Thanks to strangelookingnerd, Gary Gregory.
+o Add org.apache.commons.io.FileUtils.ONE_RB #763. Thanks to strangelookingnerd, Gary Gregory.
+o Add org.apache.commons.io.FileUtils.ONE_QB #763. Thanks to strangelookingnerd, Gary Gregory.
+o Add org.apache.commons.io.output.ProxyOutputStream.writeRepeat(byte[], int, int, long). Thanks to Gary Gregory.
+o Add org.apache.commons.io.output.ProxyOutputStream.writeRepeat(byte[], long). Thanks to Gary Gregory.
+o Add org.apache.commons.io.output.ProxyOutputStream.writeRepeat(int, long). Thanks to Gary Gregory.
+o Add length unit support in FileSystem limits. Thanks to Piotr P. Karwasz.
+o Add IOUtils.toByteArray(InputStream, int, int) for safer chunked reading with size validation. Thanks to Piotr P. Karwasz.
+o Add org.apache.commons.io.file.PathUtils.getPath(String, String). Thanks to Gary Gregory.
+o Add org.apache.commons.io.channels.ByteArraySeekableByteChannel. Thanks to Gary Gregory.
+o Add IOIterable.asIterable(). Thanks to Gary Gregory.
+o Add NIO channel support to `AbstractStreamBuilder`. Thanks to Piotr P. Karwasz.
+o Add CloseShieldChannel to close-shielded NIO Channels #786. Thanks to Piotr P. Karwasz.
+o Added IOUtils.checkFromIndexSize as a Java 8 backport of Objects.checkFromIndexSize #790. Thanks to Piotr P. Karwasz.
+
+Fixed Bugs
+----------
+
+o When testing on Java 21 and up, enable -XX:+EnableDynamicAgentLoading. Thanks to Gary Gregory.
+o When testing on Java 24 and up, don't fail FileUtilsListFilesTest for a different behavior in the JRE. Thanks to Gary Gregory.
+o ValidatingObjectInputStream does not validate dynamic proxy interfaces. Thanks to Stanislav Fort, Gary Gregory.
+o BoundedInputStream.getRemaining() now reports Long.MAX_VALUE instead of 0 when no limit is set. Thanks to Piotr P. Karwasz.
+o BoundedInputStream.available() correctly accounts for the maximum read limit. Thanks to Piotr P. Karwasz.
+o Deprecate IOUtils.readFully(InputStream, int) in favor of toByteArray(InputStream, int). Thanks to Gary Gregory, Piotr P. Karwasz.
+o IOUtils.toByteArray(InputStream) now throws IOException on byte array overflow. Thanks to Piotr P. Karwasz.
+o Javadoc general improvements. Thanks to Gary Gregory, Piotr P. Karwasz.
+o IOUtils.toByteArray() now throws EOFException when not enough data is available #796. Thanks to Piotr P. Karwasz.
+o Fix IOUtils.skip() usage in concurrent scenarios. Thanks to Piotr P. Karwasz.
+o [javadoc] Fix XmlStreamReader Javadoc to indicate the correct class that is built #806. Thanks to J Hawkins.
+
+Changes
+-------
+
+o Bump org.apache.commons:commons-parent from 85 to 91 #774, #783, #808. Thanks to Gary Gregory, Dependabot.
+o [test] Bump commons-codec:commons-codec from 1.18.0 to 1.19.0. Thanks to Gary Gregory.
+o [test] Bump commons.bytebuddy.version from 1.17.6 to 1.17.8 #769. Thanks to Gary Gregory, Dependabot.
+o [test] Bump org.apache.commons:commons-lang3 from 3.18.0 to 3.19.0. Thanks to Gary Gregory.
+
+Removed
+-------
+
+o Inline private constant field ProxyInputStream.exceptionHandler #780. Thanks to Piotr P. Karwasz.
+Commons IO 2.7 and up requires Java 8 or above.
+Commons IO 2.6 requires Java 7 or above.
+Commons IO 2.3 through 2.5 requires Java 6 or above.
+Commons IO 2.2 requires Java 5 or above.
+Commons IO 1.4 requires Java 1.3 or above.
+
+Historical list of changes: https://commons.apache.org/proper/commons-io/changes.html
+
+For complete information on Apache Commons IO, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Commons IO website:
+
+https://commons.apache.org/proper/commons-io/
+
+Download page: https://commons.apache.org/proper/commons-io/download_io.cgi
+
+Have fun!
+-Apache Commons Team
+
+------------------------------------------------------------------------------
+
+
Apache Commons IO 2.20.0 Release Notes
+--------------------------------------
The Apache Commons IO team is pleased to announce the release of Apache Commons IO 2.20.0.
@@ -78,6 +354,7 @@ Have fun!
Apache Commons IO 2.19.0 Release Notes
+--------------------------------------
Introduction
------------
@@ -173,6 +450,7 @@ Have fun!
Apache Commons IO 2.18.0 Release Notes
+--------------------------------------
Introduction
------------
@@ -251,6 +529,7 @@ Apache Commons Team
Apache Commons IO 2.17.0 Release Notes
+--------------------------------------
Introduction
------------
@@ -341,6 +620,7 @@ Have fun!
Apache Commons IO 2.16.1 Release Notes
+--------------------------------------
Introduction
------------
@@ -393,6 +673,7 @@ Have fun!
Apache Commons IO 2.16.1 Release Notes
+--------------------------------------
Introduction
------------
@@ -444,6 +725,7 @@ Have fun!
Apache Commons IO 2.16.0 Release Notes
+--------------------------------------
Introduction
------------
diff --git a/pom.xml b/pom.xml
index c356baf502a..6960ab6d941 100644
--- a/pom.xml
+++ b/pom.xml
@@ -19,12 +19,12 @@
org.apache.commonscommons-parent
- 88
+ 1024.0.0commons-iocommons-io
- 2.21.0-SNAPSHOT
+ 2.23.0-SNAPSHOTApache Commons IO2002
@@ -32,10 +32,6 @@ The Apache Commons IO library contains utility classes, stream implementations,
file comparators, endian transformation classes, and much more.
https://commons.apache.org/proper/commons-io/
-
- jira
- https://issues.apache.org/jira/browse/IO
- apache.website
@@ -43,16 +39,6 @@ file comparators, endian transformation classes, and much more.
scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-io/
-
- scm:git:https://gitbox.apache.org/repos/asf/commons-io.git
- scm:git:https://gitbox.apache.org/repos/asf/commons-io.git
- https://gitbox.apache.org/repos/asf?p=commons-io.git
- rel/commons-io-2.21.0
-
-
- GitHub
- https://github.com/apache/commons-io/actions
- org.junit.jupiter
@@ -81,7 +67,6 @@ file comparators, endian transformation classes, and much more.
org.mockitomockito-inline
- ${commons.mockito.version}test
@@ -93,13 +78,13 @@ file comparators, endian transformation classes, and much more.
org.apache.commonscommons-lang3
- 3.19.0
+ 3.20.0testcommons-codeccommons-codec
- 1.19.0
+ 1.22.0test
@@ -115,11 +100,11 @@ file comparators, endian transformation classes, and much more.
ioorg.apache.commons.ioRC1
- 2.20.0
- 2.21.0
- 2.21.1
+ 2.22.0
+ 2.23.0
+ 2.23.1
- 2025-07-18T21:12:04Z
+ 2026-04-23T10:25:32Z(requires Java 8)IO12310477
@@ -146,11 +131,10 @@ file comparators, endian transformation classes, and much more.
https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-io/site-content
- 1.17.7
+ 1.18.10falsetrue
- ${env.JACOCO_SKIP}true0.980.90
@@ -170,11 +154,11 @@ file comparators, endian transformation classes, and much more.
org.apache.ratapache-rat-plugin
-
- src/test/resources/**/*.bin
- src/test/resources/dir-equals-tests/**
- test/**
-
+
+ src/test/resources/**/*.bin
+ src/test/resources/dir-equals-tests/**
+ test/**
+
@@ -219,7 +203,7 @@ file comparators, endian transformation classes, and much more.
false
- ${argLine} -Xmx25M ${EnableDynamicAgentLoading}
+ @{argLine} -Xmx25M ${EnableDynamicAgentLoading}**/*Test*.class
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index fb68216e20a..9855d36f512 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -45,7 +45,79 @@ The type attribute can be add,update,fix,remove.
Apache Commons IO Release Notes
-
+
+
+ ThresholdingOutputStream.isThresholdExceeded() now reflects the threshold-reached state, and a failed thresholdReached() no longer leaves the stream unable to fire the event again.
+ Clean BufferedFileChannelInputStream's direct ByteBuffer only once #854.
+ BufferedFileChannelInputStream now clears its direct memory byte buffer on close (#855).
+ MemoryMappedFileInputStream now clears its direct memory byte buffer on close (#855).
+ FileChannels.contentEquals(ReadableByteChannel, ReadableByteChannel, int) now clears its direct memory byte buffer on close (#855).
+ BufferedFileChannelInputStream now clears its direct memory byte buffer on close (#855).
+ MemoryMappedFileInputStream now clears its direct memory byte buffer on close (#855).
+ Clarify PeekableInputStream.peek() behavior in Javadoc (#856).
+ DeferredFileOutputStream now clears and deletes its temporary storage by default (#858).
+ Update generic type of RandomAccessFileMode.accept(Path, IOConsumer) from IOConsumer<RandomAccessFile> to IOConsumer<IORandomAccessFile>.
+ Harden tests for NPEs on failures, happy path unchanged.
+ Fix BoundedReader.skip(long) accounting and bounds handling (#860).
+ DeferredFileOutputStream better NPE message and new file permission tests (#862).
+
+ Add IOConsumer.accept(IOConsumer, T) (#846).
+ Add UnsynchronizedBufferedReader.unwrap() (#850).
+ Add UnsynchronizedBufferedReader.getPosition() (#851).
+ Add Buffers clear() methods (#853).
+ Add DeferredFileOutputStream.Builder.setDeleteTempFileOnClose(boolean) (#858).
+ Add PathUtils.clear[IfExists](Path) (#858).
+ Add PathUtils.deleteIfExists(Path) (#858).
+ Add a strict mode to ValidatingObjectInputStream (#861).
+
+ Bump org.apache.commons:commons-parent from 98 to 102 (#849).
+ [test] Bump commons-codec:commons-codec from 1.21.0 to 1.22.0.
+ [test] Bump commons.bytebuddy.version from 1.18.8 to 1.18.10 (#4655).
+
+
+
+ Fix Apache RAT plugin console warnings.
+ ByteArraySeekableByteChannel.position(long) and truncate(long) shouldn't throw an IllegalArgumentException for a new positive position that's too large #817.
+ Fix malformed Javadoc comments.
+ ReadAheadInputStream.close() doesn't always close its filtered input stream.
+ ReadAheadInputStream now restores the current thread's interrupt flag when catching InterruptedException.
+ FileAlterationMonitor.stop(long) now restores the current thread's interrupt flag when catching InterruptedException.
+ FileCleaningTracker now restores the current thread's interrupt flag when catching InterruptedException.
+ ThreadMonitor.run() now restores the current thread's interrupt flag when catching InterruptedException.
+ ThrottledInputStream.throttle() now restores the current thread's interrupt flag when catching InterruptedException.
+ ThrottledInputStream.throttle() doesn't preserve the original InterruptedException as the cause of its InterruptedIOException.
+ All thread names are now prefixed with "commons-io-".
+ ReversedLinesFileReader does not read first line if its empty #829.
+ Fixed incorrect regular expression in PathUtils.RelativeSortedPaths.extractKey(String, String).
+ Fix typos in Javadoc of FileUtils and related test classes #833.
+ WriterOutputStream from a builder fails on malformed or unmappable input bytes.
+ BoundedReader now extends ProxyReader.
+ AbstractStreamBuilder.setOpenOptions(OpenOption...) now makes a defensive copy of its input array.
+ Path visits follow links #832.
+ BOMInputStream fail-fast and tracks its ByteOrderMark as a final #835.
+ Refactor UnixLineEndingInputStream and WindowsLineEndingInputStream for duplication.
+ [Javadoc] PathUtils.cleanDirectory() methods vs FileUtils.
+ Fix JaCoCo report generation (code coverage).
+ AbstractStreamBuilder.setBufferSizeDefault(int) now resets to default for input less than or equal to zero.
+
+ Add and use IOUtils.closeQuietlySuppress(Closeable, Throwable) #818.
+ Add ProxyWriter.setReference(Writer).
+ Add ProxyWriter.unwrap().
+ Add ProxyReader.setReference(Reader).
+ Add ProxyReader.unrwap().
+ ByteArraySeekableByteChannel should optionally configure a read-only channel.
+ Add ByteArraySeekableByteChannel.Builder and builder().
+ Add AbstractStreamBuilder.getByteArray().
+ CloseShieldInputStream now supports a custom close shield as a function #836.
+ Add FlushShieldOutputStream to workaround issues in generic code that ends up calling third parties like like org.tukaani.xz.LZMAOutputStream.flush().
+ Add filter channels.
+
+ Bump org.apache.commons:commons-parent from 91 to 98 #816.
+ Bump commons-codec:commons-codec from 1.19.0 to 1.21.0 #812.
+ Bump commons.bytebuddy.version from 1.17.8 to 1.18.8 #814, #820, #838.
+ Bump commons-lang3 from 3.19.0 to 3.20.0.
+
+ When testing on Java 21 and up, enable -XX:+EnableDynamicAgentLoading.When testing on Java 24 and up, don't fail FileUtilsListFilesTest for a different behavior in the JRE.
@@ -55,6 +127,9 @@ The type attribute can be add,update,fix,remove.
Deprecate IOUtils.readFully(InputStream, int) in favor of toByteArray(InputStream, int).IOUtils.toByteArray(InputStream) now throws IOException on byte array overflow.Javadoc general improvements.
+ IOUtils.toByteArray() now throws EOFException when not enough data is available #796.
+ Fix IOUtils.skip() usage in concurrent scenarios.
+ [javadoc] Fix XmlStreamReader Javadoc to indicate the correct class that is built #806.FileUtils#byteCountToDisplaySize() supports Zettabyte, Yottabyte, Ronnabyte and Quettabyte #763.Add org.apache.commons.io.FileUtils.ONE_RB #763.
@@ -71,9 +146,9 @@ The type attribute can be add,update,fix,remove.
Add CloseShieldChannel to close-shielded NIO Channels #786.Added IOUtils.checkFromIndexSize as a Java 8 backport of Objects.checkFromIndexSize #790.
- Bump org.apache.commons:commons-parent from 85 to 88 #774, #783.
+ Bump org.apache.commons:commons-parent from 85 to 91 #774, #783, #808.[test] Bump commons-codec:commons-codec from 1.18.0 to 1.19.0.
- [test] Bump commons.bytebuddy.version from 1.17.6 to 1.17.7 #769.
+ [test] Bump commons.bytebuddy.version from 1.17.6 to 1.17.8 #769.[test] Bump org.apache.commons:commons-lang3 from 3.18.0 to 3.19.0.Inline private constant field ProxyInputStream.exceptionHandler #780.
@@ -1340,7 +1415,7 @@ The type attribute can be add,update,fix,remove.
Fixed error of copying directories between different file systems #203.
- Fix Typos in JavaDoc, Comments and Tests #201.
+ Fix Typos in Javadoc, Comments and Tests #201.
FileUtils.checksumCRC32 and FileUtils.checksum are not thread safe.
diff --git a/src/changes/release-notes.vm b/src/changes/release-notes.vm
index c28de3c8729..aa5a3663420 100644
--- a/src/changes/release-notes.vm
+++ b/src/changes/release-notes.vm
@@ -16,6 +16,7 @@
## under the License.
Apache Commons IO ${version} Release Notes
+--------------------------------------
The ${developmentTeam} is pleased to announce the release of ${project.name} ${version}.
diff --git a/src/conf/maven-pmd-plugin.xml b/src/conf/maven-pmd-plugin.xml
index 215ac295ede..9d51e182ff9 100644
--- a/src/conf/maven-pmd-plugin.xml
+++ b/src/conf/maven-pmd-plugin.xml
@@ -78,7 +78,6 @@ under the License.
-
diff --git a/src/main/java/org/apache/commons/io/Buffers.java b/src/main/java/org/apache/commons/io/Buffers.java
new file mode 100644
index 00000000000..cd4e2a2b179
--- /dev/null
+++ b/src/main/java/org/apache/commons/io/Buffers.java
@@ -0,0 +1,299 @@
+/*
+ * 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.io;
+
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.DoubleBuffer;
+import java.nio.FloatBuffer;
+import java.nio.IntBuffer;
+import java.nio.LongBuffer;
+import java.nio.ReadOnlyBufferException;
+import java.nio.ShortBuffer;
+import java.util.Arrays;
+
+/**
+ * Helps use {@link Buffer} instances.
+ *
+ * @since 2.23.0
+ */
+public final class Buffers {
+
+ /**
+ * Clears this buffer by filling it with zeros, the position is set to zero, the limit is set to the capacity, and the mark is discarded.
+ *
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer, or null.
+ * @throws ReadOnlyBufferException If the buffer is read-only.
+ * @throws UnsupportedOperationException Thrown if the given buffer is not one of {@link CharBuffer}, {@link ByteBuffer}, {@link DoubleBuffer},
+ * {@link FloatBuffer}, {@link IntBuffer}, {@link LongBuffer}, {@link ShortBuffer}, or null.
+ */
+ public static Buffer clear(final Buffer buffer) {
+ if (buffer instanceof CharBuffer) {
+ return clear((CharBuffer) buffer);
+ }
+ if (buffer instanceof ByteBuffer) {
+ return clear((ByteBuffer) buffer);
+ }
+ if (buffer instanceof DoubleBuffer) {
+ return clear((DoubleBuffer) buffer);
+ }
+ if (buffer instanceof FloatBuffer) {
+ return clear((FloatBuffer) buffer);
+ }
+ if (buffer instanceof IntBuffer) {
+ return clear((IntBuffer) buffer);
+ }
+ if (buffer instanceof LongBuffer) {
+ return clear((LongBuffer) buffer);
+ }
+ if (buffer instanceof ShortBuffer) {
+ return clear((ShortBuffer) buffer);
+ }
+ if (buffer == null) {
+ return null;
+ }
+ throw new UnsupportedOperationException(buffer.getClass().getCanonicalName());
+ }
+
+ /**
+ * Clears this buffer by filling it with zeros, the position is set to zero, the limit is set to the capacity, and the mark is discarded.
+ *
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ * @throws ReadOnlyBufferException If the buffer is read-only.
+ */
+ public static ByteBuffer clear(final ByteBuffer buffer) {
+ if (buffer == null) {
+ return null;
+ }
+ if (clearBuffer(buffer).hasArray()) {
+ Arrays.fill(buffer.array(), (byte) 0);
+ } else {
+ final byte[] zeros = new byte[IOUtils.DEFAULT_BUFFER_SIZE];
+ while (buffer.hasRemaining()) {
+ buffer.put(zeros, 0, Math.min(buffer.remaining(), zeros.length));
+ }
+ }
+ return clearBuffer(buffer);
+ }
+
+ /**
+ * Clears this buffer by filling it with zeros, the position is set to zero, the limit is set to the capacity, and the mark is discarded.
+ *
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ * @throws ReadOnlyBufferException If the buffer is read-only.
+ */
+ public static CharBuffer clear(final CharBuffer buffer) {
+ if (buffer == null) {
+ return null;
+ }
+ if (clearBuffer(buffer).hasArray()) {
+ Arrays.fill(buffer.array(), (char) 0);
+ } else {
+ final char[] zeros = new char[IOUtils.DEFAULT_BUFFER_SIZE];
+ while (buffer.hasRemaining()) {
+ buffer.put(zeros, 0, Math.min(buffer.remaining(), zeros.length));
+ }
+ }
+ return clearBuffer(buffer);
+ }
+
+ /**
+ * Clears this buffer by filling it with zeros, the position is set to zero, the limit is set to the capacity, and the mark is discarded.
+ *
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ * @throws ReadOnlyBufferException If the buffer is read-only.
+ */
+ public static DoubleBuffer clear(final DoubleBuffer buffer) {
+ if (buffer == null) {
+ return null;
+ }
+ if (clearBuffer(buffer).hasArray()) {
+ Arrays.fill(buffer.array(), 0);
+ } else {
+ final double[] zeros = new double[IOUtils.DEFAULT_BUFFER_SIZE];
+ while (buffer.hasRemaining()) {
+ buffer.put(zeros, 0, Math.min(buffer.remaining(), zeros.length));
+ }
+ }
+ return clearBuffer(buffer);
+ }
+
+ /**
+ * Clears this buffer by filling it with zeros, the position is set to zero, the limit is set to the capacity, and the mark is discarded.
+ *
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ * @throws ReadOnlyBufferException If the buffer is read-only.
+ */
+ public static FloatBuffer clear(final FloatBuffer buffer) {
+ if (buffer == null) {
+ return null;
+ }
+ if (clearBuffer(buffer).hasArray()) {
+ Arrays.fill(buffer.array(), 0);
+ } else {
+ final float[] zeros = new float[IOUtils.DEFAULT_BUFFER_SIZE];
+ while (buffer.hasRemaining()) {
+ buffer.put(zeros, 0, Math.min(buffer.remaining(), zeros.length));
+ }
+ }
+ return clearBuffer(buffer);
+ }
+
+ /**
+ * Clears this buffer by filling it with zeros, the position is set to zero, the limit is set to the capacity, and the mark is discarded.
+ *
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ * @throws ReadOnlyBufferException If the buffer is read-only.
+ */
+ public static IntBuffer clear(final IntBuffer buffer) {
+ if (buffer == null) {
+ return null;
+ }
+ if (clearBuffer(buffer).hasArray()) {
+ Arrays.fill(buffer.array(), 0);
+ } else {
+ final int[] zeros = new int[IOUtils.DEFAULT_BUFFER_SIZE];
+ while (buffer.hasRemaining()) {
+ buffer.put(zeros, 0, Math.min(buffer.remaining(), zeros.length));
+ }
+ }
+ return clearBuffer(buffer);
+ }
+
+ /**
+ * Clears this buffer by filling it with zeros, the position is set to zero, the limit is set to the capacity, and the mark is discarded.
+ *
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ * @throws ReadOnlyBufferException If the buffer is read-only.
+ */
+ public static LongBuffer clear(final LongBuffer buffer) {
+ if (buffer == null) {
+ return null;
+ }
+ if (clearBuffer(buffer).hasArray()) {
+ Arrays.fill(buffer.array(), 0);
+ } else {
+ final long[] zeros = new long[IOUtils.DEFAULT_BUFFER_SIZE];
+ while (buffer.hasRemaining()) {
+ buffer.put(zeros, 0, Math.min(buffer.remaining(), zeros.length));
+ }
+ }
+ return clearBuffer(buffer);
+ }
+
+ /**
+ * Clears this buffer by filling it with zeros, the position is set to zero, the limit is set to the capacity, and the mark is discarded.
+ *
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ * @throws ReadOnlyBufferException If the buffer is read-only.
+ */
+ public static ShortBuffer clear(final ShortBuffer buffer) {
+ if (buffer == null) {
+ return null;
+ }
+ if (clearBuffer(buffer).hasArray()) {
+ Arrays.fill(buffer.array(), (short) 0);
+ } else {
+ final short[] zeros = new short[IOUtils.DEFAULT_BUFFER_SIZE];
+ while (buffer.hasRemaining()) {
+ buffer.put(zeros, 0, Math.min(buffer.remaining(), zeros.length));
+ }
+ }
+ return clearBuffer(buffer);
+ }
+
+ /**
+ * A better typed version of {@link Buffer#clear()}.
+ *
+ * Clears this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded.
+ *
+ *
+ * Invoke this method before using a sequence of channel-read or put operations to fill this buffer. For example:
+ *
+ *
+ *
+ * buf.clear(); // Prepare buffer for reading
+ * in.read(buf); // Read data
+ *
+ *
+ *
+ * This method does not actually erase the data in the buffer, but it is named as if it did because it will most often be used in situations in which that
+ * might as well be the case.
+ *
+ *
+ * @param A Buffer subclass.
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ */
+ private static B clearBuffer(final B buffer) {
+ buffer.clear();
+ return buffer;
+ }
+
+ /**
+ * Clears the given direct buffer by filling it with zeros and resetting the position to zero. The limit is set to the capacity of the buffer.
+ *
+ * If the given buffer is a not direct buffer, nothing happens to that buffer.
+ *
+ *
+ * @param A Buffer subclass.
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ */
+ public static B clearDirect(final B buffer) {
+ if (buffer != null && buffer.isDirect()) {
+ clear(buffer);
+ }
+ return buffer;
+ }
+
+ /**
+ * Clears the given writable buffer by filling it with zeros and resetting the position to zero. The limit is set to the capacity of the buffer.
+ *
+ * If the buffer is read-only, then nothing happens to that buffer.
+ *
+ *
+ * @param A Buffer subclass.
+ * @param buffer The buffer to clear, may be null.
+ * @return The given buffer.
+ */
+ public static B clearWritable(final B buffer) {
+ if (buffer != null && !buffer.isReadOnly()) {
+ clear(buffer);
+ }
+ return buffer;
+ }
+
+ /**
+ * No instances.
+ */
+ private Buffers() {
+ // empty.
+ }
+}
diff --git a/src/main/java/org/apache/commons/io/ByteBuffers.java b/src/main/java/org/apache/commons/io/ByteBuffers.java
index 91efd8ed3e2..4eab647a78b 100644
--- a/src/main/java/org/apache/commons/io/ByteBuffers.java
+++ b/src/main/java/org/apache/commons/io/ByteBuffers.java
@@ -47,7 +47,7 @@ public static ByteBuffer littleEndian(final byte[] array) {
* Sets the give buffer to little-endian.
*
* @param allocate The buffer to set to little-endian.
- * @return the given buffer.
+ * @return The given buffer.
*/
public static ByteBuffer littleEndian(final ByteBuffer allocate) {
return allocate.order(ByteOrder.LITTLE_ENDIAN);
@@ -68,8 +68,11 @@ public static ByteBuffer littleEndian(final int capacity) {
return littleEndian(ByteBuffer.allocate(capacity));
}
+ /**
+ * No instances.
+ */
private ByteBuffers() {
- // empty, no instance.
+ // empty.
}
}
diff --git a/src/main/java/org/apache/commons/io/ByteOrderMark.java b/src/main/java/org/apache/commons/io/ByteOrderMark.java
index 0067f7d2d6f..98726b609c3 100644
--- a/src/main/java/org/apache/commons/io/ByteOrderMark.java
+++ b/src/main/java/org/apache/commons/io/ByteOrderMark.java
@@ -40,7 +40,7 @@
*
* @see org.apache.commons.io.input.BOMInputStream
* @see Wikipedia: Byte Order Mark
- * @see W3C: Autodetection of Character Encodings
+ * @see W3C: Autodetection of Character Encodings
* (Non-Normative)
* @since 2.0
*/
@@ -128,10 +128,10 @@ public class ByteOrderMark implements Serializable {
/**
* Constructs a new instance.
*
- * @param charsetName The name of the charset the BOM represents
- * @param bytes The BOM's bytes
- * @throws IllegalArgumentException if the charsetName is zero length
- * @throws IllegalArgumentException if the bytes are zero length
+ * @param charsetName The name of the charset the BOM represents.
+ * @param bytes The BOM's bytes.
+ * @throws IllegalArgumentException if the charsetName is zero length.
+ * @throws IllegalArgumentException if the bytes are zero length.
*/
public ByteOrderMark(final String charsetName, final int... bytes) {
Objects.requireNonNull(charsetName, "charsetName");
@@ -149,9 +149,9 @@ public ByteOrderMark(final String charsetName, final int... bytes) {
/**
* Indicates if this instance's bytes equals another.
*
- * @param obj The object to compare to
+ * @param obj The object to compare to.
* @return true if the bom's bytes are equal, otherwise
- * false
+ * false.
*/
@Override
public boolean equals(final Object obj) {
@@ -173,8 +173,8 @@ public boolean equals(final Object obj) {
/**
* Gets the byte at the specified position.
*
- * @param pos The position
- * @return The specified byte
+ * @param pos The position.
+ * @return The specified byte.
*/
public int get(final int pos) {
return bytes[pos];
@@ -183,7 +183,7 @@ public int get(final int pos) {
/**
* Gets a copy of the BOM's bytes.
*
- * @return a copy of the BOM's bytes
+ * @return A copy of the BOM's bytes.
*/
public byte[] getBytes() {
final byte[] copy = IOUtils.byteArray(bytes.length);
@@ -196,7 +196,7 @@ public byte[] getBytes() {
/**
* Gets the name of the {@link java.nio.charset.Charset} the BOM represents.
*
- * @return the character set name
+ * @return The character set name.
*/
public String getCharsetName() {
return charsetName;
@@ -209,7 +209,7 @@ int[] getRawBytes() {
/**
* Computes the hash code for this BOM.
*
- * @return the hash code for this BOM.
+ * @return The hash code for this BOM.
* @see Object#hashCode()
*/
@Override
@@ -224,7 +224,7 @@ public int hashCode() {
/**
* Gets the length of the BOM's bytes.
*
- * @return the length of the BOM's bytes
+ * @return The length of the BOM's bytes.
*/
public int length() {
return bytes.length;
@@ -233,7 +233,7 @@ public int length() {
/**
* Tests whether the given array starts with the bytes for this BOM.
*
- * @param test the array to test.
+ * @param test The array to test.
* @return whether the given array starts with the bytes for this BOM.
* @since 2.19.0
*/
@@ -260,7 +260,7 @@ public boolean matches(final int[] test) {
/**
* Converts this instance to a String representation of the BOM.
*
- * @return the length of the BOM's bytes
+ * @return The length of the BOM's bytes.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/ByteOrderParser.java b/src/main/java/org/apache/commons/io/ByteOrderParser.java
index 33a263e4966..1676ee8d093 100644
--- a/src/main/java/org/apache/commons/io/ByteOrderParser.java
+++ b/src/main/java/org/apache/commons/io/ByteOrderParser.java
@@ -41,8 +41,8 @@ public final class ByteOrderParser {
*
*
* @param value
- * the {@link String} containing the ByteOrder representation to be parsed
- * @return the ByteOrder represented by the string argument
+ * the {@link String} containing the ByteOrder representation to be parsed.
+ * @return The ByteOrder represented by the string argument.
* @throws IllegalArgumentException
* if the {@link String} containing the ByteOrder representation to be parsed is unknown.
*/
diff --git a/src/main/java/org/apache/commons/io/Charsets.java b/src/main/java/org/apache/commons/io/Charsets.java
index ef6a6264f77..a5afe4b8a44 100644
--- a/src/main/java/org/apache/commons/io/Charsets.java
+++ b/src/main/java/org/apache/commons/io/Charsets.java
@@ -34,21 +34,38 @@
* documentation for your implementation to see if any other encodings are supported.
*
*
- *
- *
{@code US-ASCII}
- * Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set.
- *
{@code ISO-8859-1}
- * ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.
{@code UTF-16}
- * Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either order
- * accepted on input, big-endian used on output.)
- *
+ *
+ *
Standard Charsets
+ *
+ *
Charset
+ *
Description
+ *
+ *
+ *
{@code US-ASCII}
+ *
Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set.
+ *
+ *
+ *
{@code ISO-8859-1}
+ *
ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1.
+ *
+ *
+ *
{@code UTF-8}
+ *
Eight-bit Unicode Transformation Format.
+ *
+ *
+ *
{@code UTF-16BE}
+ *
Sixteen-bit Unicode Transformation Format, big-endian byte order.
+ *
+ *
+ *
{@code UTF-16LE}
+ *
Sixteen-bit Unicode Transformation Format, little-endian byte order.
+ *
+ *
+ *
{@code UTF-16}
+ *
Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either order
+ * accepted on input, big-endian used on output.)
+ *
+ *
*
* @see Standard charsets
* @since 2.3
@@ -80,7 +97,7 @@ public class Charsets {
*
*
* @see Standard charsets
- * @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
+ * @deprecated Use {@link java.nio.charset.StandardCharsets#ISO_8859_1}.
*/
@Deprecated
public static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1;
@@ -94,7 +111,7 @@ public class Charsets {
*
*
* @see Standard charsets
- * @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
+ * @deprecated Use {@link java.nio.charset.StandardCharsets#US_ASCII}.
*/
@Deprecated
public static final Charset US_ASCII = StandardCharsets.US_ASCII;
@@ -109,7 +126,7 @@ public class Charsets {
*
*
* @see Standard charsets
- * @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
+ * @deprecated Use {@link java.nio.charset.StandardCharsets#UTF_16}.
*/
@Deprecated
public static final Charset UTF_16 = StandardCharsets.UTF_16;
@@ -123,7 +140,7 @@ public class Charsets {
*
*
* @see Standard charsets
- * @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
+ * @deprecated Use {@link java.nio.charset.StandardCharsets#UTF_16BE}.
*/
@Deprecated
public static final Charset UTF_16BE = StandardCharsets.UTF_16BE;
@@ -137,7 +154,7 @@ public class Charsets {
*
*
* @see Standard charsets
- * @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
+ * @deprecated Use {@link java.nio.charset.StandardCharsets#UTF_16LE}.
*/
@Deprecated
public static final Charset UTF_16LE = StandardCharsets.UTF_16LE;
@@ -151,7 +168,7 @@ public class Charsets {
*
*
* @see Standard charsets
- * @deprecated Use Java 7's {@link java.nio.charset.StandardCharsets}
+ * @deprecated Use {@link java.nio.charset.StandardCharsets#UTF_8}.
*/
@Deprecated
public static final Charset UTF_8 = StandardCharsets.UTF_8;
@@ -159,7 +176,7 @@ public class Charsets {
/**
* Tests whether the given non-null Charset has an alias of the given name.
*
- * @param charset a non-null Charset.
+ * @param charset A non-null Charset.
* @param charsetName The name to test.
* @return whether the given non-null charset name is a UTF-8 alias.
* @since 2.20.0
@@ -182,7 +199,7 @@ public static boolean isUTF8(final Charset charset) {
/**
* Tests whether the given non-null charset name is a UTF-8 alias.
*
- * @param charsetName a non-null charset name.
+ * @param charsetName A non-null charset name.
* @return whether the given non-null charset name is a UTF-8 alias.
*/
private static boolean isUTF8Alias(final String charsetName) {
@@ -210,7 +227,7 @@ public static SortedMap requiredCharsets() {
*
* @param charset
* A charset or null.
- * @return the given Charset or the default Charset if the given Charset is null
+ * @return The given Charset or the default Charset if the given Charset is null.
* @see Charset#defaultCharset()
*/
public static Charset toCharset(final Charset charset) {
@@ -222,7 +239,7 @@ public static Charset toCharset(final Charset charset) {
*
* @param charset The charset to test, may be null.
* @param defaultCharset The charset to return if charset is null, may be null.
- * @return a Charset.
+ * @return A Charset.
* @since 2.12.0
*/
public static Charset toCharset(final Charset charset, final Charset defaultCharset) {
@@ -233,7 +250,7 @@ public static Charset toCharset(final Charset charset, final Charset defaultChar
* Returns a Charset for the named charset. If the name is null, return the {@link Charset#defaultCharset() default Charset}.
*
* @param charsetName The name of the requested charset, may be null.
- * @return a Charset for the named charset.
+ * @return A Charset for the named charset.
* @throws UnsupportedCharsetException If the named charset is unavailable (unchecked exception).
* @see Charset#defaultCharset()
*/
@@ -246,7 +263,7 @@ public static Charset toCharset(final String charsetName) throws UnsupportedChar
*
* @param charsetName The name of the requested charset, may be null.
* @param defaultCharset The charset to return if charsetName is null, may be null.
- * @return a Charset for the named charset.
+ * @return A Charset for the named charset.
* @throws UnsupportedCharsetException If the named charset is unavailable (unchecked exception).
* @since 2.12.0
*/
@@ -262,7 +279,7 @@ public static Charset toCharset(final String charsetName, final Charset defaultC
*
* @param charsetName The name of the requested charset, may be null.
* @param defaultCharset The charset to return if charsetName is null or there is a problem, may be null which returns {@link Charset#defaultCharset()}.
- * @return a Charset for the named charset or {@code defaultCharset} if any errors occur.
+ * @return A Charset for the named charset or {@code defaultCharset} if any errors occur.
* @see Charset#defaultCharset()
* @since 2.20.0
*/
@@ -277,7 +294,7 @@ public static Charset toCharsetDefault(final String charsetName, final Charset d
/**
* Construct a new instance.
*
- * @deprecated Will be private in 4.0
+ * @deprecated Will be private in 3.0.
*/
@Deprecated
public Charsets() {
diff --git a/src/main/java/org/apache/commons/io/CopyUtils.java b/src/main/java/org/apache/commons/io/CopyUtils.java
index ad426952e4e..c81a380d1ee 100644
--- a/src/main/java/org/apache/commons/io/CopyUtils.java
+++ b/src/main/java/org/apache/commons/io/CopyUtils.java
@@ -29,6 +29,8 @@
import java.io.Writer;
import java.nio.charset.Charset;
+import org.apache.commons.io.IOUtils.ScratchChars;
+
/**
* This class provides static utility methods for buffered
* copying between sources ({@link InputStream}, {@link Reader},
@@ -44,7 +46,7 @@
* released when the associated Stream is garbage-collected. It is not a good
* idea to rely on this mechanism. For a good overview of the distinction
* between "memory management" and "resource management", see
- * this
+ * this
* UnixReview article.
*
* For byte-to-char methods, a {@code copy} variant allows the encoding
@@ -115,9 +117,10 @@ public class CopyUtils {
/**
* Copies bytes from a {@code byte[]} to an {@link OutputStream}.
- * @param input the byte array to read from
- * @param output the {@link OutputStream} to write to
- * @throws IOException In case of an I/O problem
+ *
+ * @param input The byte array to read from.
+ * @param output The {@link OutputStream} to write to.
+ * @throws IOException In case of an I/O problem.
*/
public static void copy(final byte[] input, final OutputStream output) throws IOException {
output.write(input);
@@ -128,10 +131,10 @@ public static void copy(final byte[] input, final OutputStream output) throws IO
* {@link Writer}.
* The platform's default encoding is used for the byte-to-char conversion.
*
- * @param input the byte array to read from
- * @param output the {@link Writer} to write to
- * @throws IOException In case of an I/O problem
- * @deprecated Use {@link #copy(byte[], Writer, String)} instead
+ * @param input The byte array to read from.
+ * @param output The {@link Writer} to write to.
+ * @throws IOException In case of an I/O problem.
+ * @deprecated Use {@link #copy(byte[], Writer, String)} instead.
*/
@Deprecated
public static void copy(final byte[] input, final Writer output) throws IOException {
@@ -143,12 +146,12 @@ public static void copy(final byte[] input, final Writer output) throws IOExcept
* Copies and convert bytes from a {@code byte[]} to chars on a
* {@link Writer}, using the specified encoding.
*
- * @param input the byte array to read from
- * @param output the {@link Writer} to write to
+ * @param input The byte array to read from.
+ * @param output The {@link Writer} to write to.
* @param encoding The name of a supported character encoding. See the
- * IANA
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @throws IOException In case of an I/O problem
+ * @throws IOException In case of an I/O problem.
*/
public static void copy(final byte[] input, final Writer output, final String encoding) throws IOException {
final ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
@@ -159,10 +162,10 @@ public static void copy(final byte[] input, final Writer output, final String en
* Copies bytes from an {@link InputStream} to an
* {@link OutputStream}.
*
- * @param input the {@link InputStream} to read from
- * @param output the {@link OutputStream} to write to
- * @return the number of bytes copied
- * @throws IOException In case of an I/O problem
+ * @param input The {@link InputStream} to read from.
+ * @param output The {@link OutputStream} to write to.
+ * @return The number of bytes copied.
+ * @throws IOException In case of an I/O problem.
*/
public static int copy(final InputStream input, final OutputStream output) throws IOException {
final byte[] buffer = IOUtils.byteArray();
@@ -179,13 +182,13 @@ public static int copy(final InputStream input, final OutputStream output) throw
* Copies and convert bytes from an {@link InputStream} to chars on a
* {@link Writer}.
*
- * This method uses the virtual machine's {@link Charset#defaultCharset() default charset} for byte-to-char conversion.
+ * This method uses the virtual machine's {@linkplain Charset#defaultCharset() default charset} for byte-to-char conversion.
*
*
- * @param input the {@link InputStream} to read from
- * @param output the {@link Writer} to write to
- * @throws IOException In case of an I/O problem
- * @deprecated Use {@link #copy(InputStream, Writer, String)} instead
+ * @param input The {@link InputStream} to read from.
+ * @param output The {@link Writer} to write to.
+ * @throws IOException In case of an I/O problem.
+ * @deprecated Use {@link #copy(InputStream, Writer, String)} instead.
*/
@Deprecated
public static void copy(
@@ -201,12 +204,12 @@ public static void copy(
* Copies and convert bytes from an {@link InputStream} to chars on a
* {@link Writer}, using the specified encoding.
*
- * @param input the {@link InputStream} to read from
- * @param output the {@link Writer} to write to
+ * @param input The {@link InputStream} to read from.
+ * @param output The {@link Writer} to write to.
* @param encoding The name of a supported character encoding. See the
- * IANA
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @throws IOException In case of an I/O problem
+ * @throws IOException In case of an I/O problem.
*/
public static void copy(
final InputStream input,
@@ -221,13 +224,13 @@ public static void copy(
* Serialize chars from a {@link Reader} to bytes on an
* {@link OutputStream}, and flush the {@link OutputStream}.
*
- * This method uses the virtual machine's {@link Charset#defaultCharset() default charset} for byte-to-char conversion.
+ * This method uses the virtual machine's {@linkplain Charset#defaultCharset() default charset} for byte-to-char conversion.
*
*
- * @param input the {@link Reader} to read from
- * @param output the {@link OutputStream} to write to
- * @throws IOException In case of an I/O problem
- * @deprecated Use {@link #copy(Reader, OutputStream, String)} instead
+ * @param input The {@link Reader} to read from.
+ * @param output The {@link OutputStream} to write to.
+ * @throws IOException In case of an I/O problem.
+ * @deprecated Use {@link #copy(Reader, OutputStream, String)} instead.
*/
@Deprecated
public static void copy(
@@ -246,12 +249,12 @@ public static void copy(
* Serialize chars from a {@link Reader} to bytes on an
* {@link OutputStream}, and flush the {@link OutputStream}.
*
- * @param input the {@link Reader} to read from
- * @param output the {@link OutputStream} to write to
+ * @param input The {@link Reader} to read from.
+ * @param output The {@link OutputStream} to write to.
* @param encoding The name of a supported character encoding. See the
- * IANA
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @throws IOException In case of an I/O problem
+ * @throws IOException In case of an I/O problem.
* @since 2.5
*/
public static void copy(
@@ -269,23 +272,25 @@ public static void copy(
/**
* Copies chars from a {@link Reader} to a {@link Writer}.
*
- * @param input the {@link Reader} to read from
- * @param output the {@link Writer} to write to
- * @return the number of characters copied
- * @throws IOException In case of an I/O problem
+ * @param input The {@link Reader} to read from.
+ * @param output The {@link Writer} to write to.
+ * @return The number of characters copied.
+ * @throws IOException In case of an I/O problem.
*/
public static int copy(
final Reader input,
final Writer output)
throws IOException {
- final char[] buffer = IOUtils.getScratchCharArray();
- int count = 0;
- int n;
- while (EOF != (n = input.read(buffer))) {
- output.write(buffer, 0, n);
- count += n;
+ try (ScratchChars scratch = IOUtils.ScratchChars.get()) {
+ final char[] buffer = scratch.array();
+ int count = 0;
+ int n;
+ while (EOF != (n = input.read(buffer))) {
+ output.write(buffer, 0, n);
+ count += n;
+ }
+ return count;
}
- return count;
}
/**
@@ -293,13 +298,13 @@ public static int copy(
* {@link OutputStream}, and
* flush the {@link OutputStream}.
*
- * This method uses the virtual machine's {@link Charset#defaultCharset() default charset} for byte-to-char conversion.
+ * This method uses the virtual machine's {@linkplain Charset#defaultCharset() default charset} for byte-to-char conversion.
*
*
- * @param input the {@link String} to read from
- * @param output the {@link OutputStream} to write to
- * @throws IOException In case of an I/O problem
- * @deprecated Use {@link #copy(String, OutputStream, String)} instead
+ * @param input The {@link String} to read from.
+ * @param output The {@link OutputStream} to write to.
+ * @throws IOException In case of an I/O problem.
+ * @deprecated Use {@link #copy(String, OutputStream, String)} instead.
*/
@Deprecated
public static void copy(
@@ -320,12 +325,12 @@ public static void copy(
* {@link OutputStream}, and
* flush the {@link OutputStream}.
*
- * @param input the {@link String} to read from
- * @param output the {@link OutputStream} to write to
+ * @param input The {@link String} to read from.
+ * @param output The {@link OutputStream} to write to.
* @param encoding The name of a supported character encoding. See the
- * IANA
+ * IANA
* Charset Registry for a list of valid encoding types.
- * @throws IOException In case of an I/O problem
+ * @throws IOException In case of an I/O problem.
* @since 2.5
*/
public static void copy(
@@ -344,9 +349,9 @@ public static void copy(
/**
* Copies chars from a {@link String} to a {@link Writer}.
*
- * @param input the {@link String} to read from
- * @param output the {@link Writer} to write to
- * @throws IOException In case of an I/O problem
+ * @param input The {@link String} to read from.
+ * @param output The {@link Writer} to write to.
+ * @throws IOException In case of an I/O problem.
*/
public static void copy(final String input, final Writer output)
throws IOException {
diff --git a/src/main/java/org/apache/commons/io/DirectoryWalker.java b/src/main/java/org/apache/commons/io/DirectoryWalker.java
index ac3d8bd5fd7..e751e6ed819 100644
--- a/src/main/java/org/apache/commons/io/DirectoryWalker.java
+++ b/src/main/java/org/apache/commons/io/DirectoryWalker.java
@@ -167,7 +167,7 @@
*
*
The decision logic on whether to cancel processing or not.
*
Constructing and throwing a {@link CancelException}.
- *
Custom cancel processing in the {@code handleCancelled()} method.
+ *
Custom cancel processing in the {@code handleCancelled()} method.
*
*
* Two possible scenarios are envisaged for cancellation:
@@ -196,14 +196,14 @@
*
* public class FooDirectoryWalker extends DirectoryWalker {
*
- * private volatile boolean cancelled = false;
+ * private volatile boolean canceled = false;
*
* public void cancel() {
- * cancelled = true;
+ * canceled = true;
* }
*
* protected boolean handleIsCancelled(File file, int depth, Collection results) {
- * return cancelled;
+ * return canceled;
* }
*
* protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) {
@@ -265,6 +265,7 @@ public static class CancelException extends IOException {
/** The file being processed when the exception was thrown. */
private final File file;
+
/** The file depth when the exception was thrown. */
private final int depth;
@@ -272,8 +273,8 @@ public static class CancelException extends IOException {
* Constructs a {@link CancelException} with
* the file and depth when cancellation occurred.
*
- * @param file the file when the operation was cancelled, may be null
- * @param depth the depth when the operation was cancelled, may be null
+ * @param file The file when the operation was canceled, may be null.
+ * @param depth The depth when the operation was canceled, may be null.
*/
public CancelException(final File file, final int depth) {
this("Operation Cancelled", file, depth);
@@ -284,9 +285,9 @@ public CancelException(final File file, final int depth) {
* an appropriate message and the file and depth when
* cancellation occurred.
*
- * @param message the detail message
- * @param file the file when the operation was cancelled
- * @param depth the depth when the operation was cancelled
+ * @param message The detail message.
+ * @param file The file when the operation was canceled.
+ * @param depth The depth when the operation was canceled.
*/
public CancelException(final String message, final File file, final int depth) {
super(message);
@@ -295,23 +296,24 @@ public CancelException(final String message, final File file, final int depth) {
}
/**
- * Returns the depth when the operation was cancelled.
+ * Returns the depth when the operation was canceled.
*
- * @return the depth when the operation was cancelled
+ * @return The depth when the operation was canceled.
*/
public int getDepth() {
return depth;
}
/**
- * Returns the file when the operation was cancelled.
+ * Returns the file when the operation was canceled.
*
- * @return the file when the operation was cancelled
+ * @return The file when the operation was canceled.
*/
public File getFile() {
return file;
}
}
+
/**
* The file filter to use to filter files and directories.
*/
@@ -338,9 +340,9 @@ protected DirectoryWalker() {
* filtering should occur and all files and directories will be visited.
*
*
- * @param filter the filter to apply, null means visit all files
+ * @param filter The filter to apply, null means visit all files.
* @param depthLimit controls how deep the hierarchy is
- * navigated to (less than 0 means unlimited)
+ * navigated to (less than 0 means unlimited).
*/
protected DirectoryWalker(final FileFilter filter, final int depthLimit) {
this.filter = filter;
@@ -357,10 +359,10 @@ protected DirectoryWalker(final FileFilter filter, final int depthLimit) {
* A {@code null} filter means that no filtering should occur.
*
*
- * @param directoryFilter the filter to apply to directories, null means visit all directories
- * @param fileFilter the filter to apply to files, null means visit all files
+ * @param directoryFilter The filter to apply to directories, null means visit all directories.
+ * @param fileFilter The filter to apply to files, null means visit all files.
* @param depthLimit controls how deep the hierarchy is
- * navigated to (less than 0 means unlimited)
+ * navigated to (less than 0 means unlimited).
*/
protected DirectoryWalker(IOFileFilter directoryFilter, IOFileFilter fileFilter, final int depthLimit) {
if (directoryFilter == null && fileFilter == null) {
@@ -376,7 +378,7 @@ protected DirectoryWalker(IOFileFilter directoryFilter, IOFileFilter fileFilter,
}
/**
- * Checks whether the walk has been cancelled by calling {@link #handleIsCancelled},
+ * Checks whether the walk has been canceled by calling {@link #handleIsCancelled},
* throwing a {@link CancelException} if it has.
*
* Writers of subclasses should not normally call this method as it is called
@@ -385,10 +387,10 @@ protected DirectoryWalker(IOFileFilter directoryFilter, IOFileFilter fileFilter,
* you may wish to check for cancellation by calling this method.
*
*
- * @param file the current file being processed
- * @param depth the current file level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
+ * @param file The current file being processed.
+ * @param depth The current file level (starting directory = 0).
+ * @param results The collection of result objects, may be updated.
+ * @throws IOException if an I/O Error occurs.
*/
protected final void checkIfCancelled(final File file, final int depth, final Collection results) throws
IOException {
@@ -403,11 +405,11 @@ protected final void checkIfCancelled(final File file, final int depth, final Co
* This implementation returns the files unchanged
*
*
- * @param directory the current directory being processed
- * @param depth the current directory level (starting directory = 0)
- * @param files the files (possibly filtered) in the directory, may be {@code null}
- * @return the filtered list of files
- * @throws IOException if an I/O Error occurs
+ * @param directory The current directory being processed.
+ * @param depth The current directory level (starting directory = 0).
+ * @param files The files (possibly filtered) in the directory, may be {@code null}
+ * @return The filtered list of files.
+ * @throws IOException if an I/O Error occurs.
* @since 2.0
*/
@SuppressWarnings("unused") // Possibly thrown from subclasses.
@@ -417,18 +419,18 @@ protected File[] filterDirectoryContents(final File directory, final int depth,
}
/**
- * Overridable callback method invoked when the operation is cancelled.
+ * Overridable callback method invoked when the operation is canceled.
* The file being processed when the cancellation occurred can be
* obtained from the exception.
*
* This implementation just re-throws the {@link CancelException}.
*
*
- * @param startDirectory the directory that the walk started from
- * @param results the collection of result objects, may be updated
- * @param cancel the exception throw to cancel further processing
+ * @param startDirectory The directory that the walk started from.
+ * @param results The collection of result objects, may be updated.
+ * @param cancel The exception throw to cancel further processing
* containing details at the point of cancellation.
- * @throws IOException if an I/O Error occurs
+ * @throws IOException if an I/O Error occurs.
*/
protected void handleCancelled(final File startDirectory, final Collection results,
final CancelException cancel) throws IOException {
@@ -447,11 +449,11 @@ protected void handleCancelled(final File startDirectory, final Collection re
* This implementation does nothing and returns true.
*
*
- * @param directory the current directory being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @return true to process this directory, false to skip this directory
- * @throws IOException if an I/O Error occurs
+ * @param directory The current directory being processed.
+ * @param depth The current directory level (starting directory = 0).
+ * @param results The collection of result objects, may be updated.
+ * @return true to process this directory, false to skip this directory.
+ * @throws IOException if an I/O Error occurs.
*/
@SuppressWarnings("unused") // Possibly thrown from subclasses.
protected boolean handleDirectory(final File directory, final int depth, final Collection results) throws
@@ -466,10 +468,10 @@ protected boolean handleDirectory(final File directory, final int depth, final C
* This implementation does nothing.
*
*
- * @param directory the directory being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
+ * @param directory The directory being processed.
+ * @param depth The current directory level (starting directory = 0).
+ * @param results The collection of result objects, may be updated.
+ * @throws IOException if an I/O Error occurs.
*/
@SuppressWarnings("unused") // Possibly thrown from subclasses.
protected void handleDirectoryEnd(final File directory, final int depth, final Collection results) throws
@@ -483,10 +485,10 @@ protected void handleDirectoryEnd(final File directory, final int depth, final C
* This implementation does nothing.
*
*
- * @param directory the current directory being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
+ * @param directory The current directory being processed.
+ * @param depth The current directory level (starting directory = 0).
+ * @param results The collection of result objects, may be updated.
+ * @throws IOException if an I/O Error occurs.
*/
@SuppressWarnings("unused") // Possibly thrown from subclasses.
protected void handleDirectoryStart(final File directory, final int depth, final Collection results) throws
@@ -500,8 +502,8 @@ protected void handleDirectoryStart(final File directory, final int depth, final
* This implementation does nothing.
*
*
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
+ * @param results The collection of result objects, may be updated.
+ * @throws IOException if an I/O Error occurs.
*/
@SuppressWarnings("unused") // Possibly thrown from subclasses.
protected void handleEnd(final Collection results) throws IOException {
@@ -514,10 +516,10 @@ protected void handleEnd(final Collection results) throws IOException {
* This implementation does nothing.
*
*
- * @param file the current file being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
+ * @param file The current file being processed.
+ * @param depth The current directory level (starting directory = 0).
+ * @param results The collection of result objects, may be updated.
+ * @throws IOException if an I/O Error occurs.
*/
@SuppressWarnings("unused") // Possibly thrown from subclasses.
protected void handleFile(final File file, final int depth, final Collection results) throws IOException {
@@ -526,7 +528,7 @@ protected void handleFile(final File file, final int depth, final Collection
/**
* Overridable callback method invoked to determine if the entire walk
- * operation should be immediately cancelled.
+ * operation should be immediately canceled.
*
* This method should be implemented by those subclasses that want to
* provide a public {@code cancel()} method available from another
@@ -534,13 +536,13 @@ protected void handleFile(final File file, final int depth, final Collection
*
* If this method returns true, then the directory walk is immediately
- * cancelled. The next callback method will be {@link #handleCancelled}.
+ * canceled. The next callback method will be {@link #handleCancelled}.
*
*
* This implementation returns false.
*
*
- * @param file the file or directory being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @return true if the walk has been cancelled
- * @throws IOException if an I/O Error occurs
+ * @param file The file or directory being processed.
+ * @param depth The current directory level (starting directory = 0).
+ * @param results The collection of result objects, may be updated.
+ * @return true if the walk has been canceled.
+ * @throws IOException if an I/O Error occurs.
*/
@SuppressWarnings("unused") // Possibly thrown from subclasses.
protected boolean handleIsCancelled(
final File file, final int depth, final Collection results) throws IOException {
// do nothing - overridable by subclass
- return false; // not cancelled
+ return false; // not canceled
}
/**
@@ -575,10 +577,10 @@ protected boolean handleIsCancelled(
* This implementation does nothing.
*
*
- * @param directory the restricted directory
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
+ * @param directory The restricted directory.
+ * @param depth The current directory level (starting directory = 0).
+ * @param results The collection of result objects, may be updated.
+ * @throws IOException if an I/O Error occurs.
*/
@SuppressWarnings("unused") // Possibly thrown from subclasses.
protected void handleRestricted(final File directory, final int depth, final Collection results) throws
@@ -592,9 +594,9 @@ protected void handleRestricted(final File directory, final int depth, final Col
* This implementation does nothing.
*
*
- * @param startDirectory the directory to start from
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
+ * @param startDirectory The directory to start from.
+ * @param results The collection of result objects, may be updated.
+ * @throws IOException if an I/O Error occurs.
*/
@SuppressWarnings("unused") // Possibly thrown from subclasses.
protected void handleStart(final File startDirectory, final Collection results) throws IOException {
@@ -613,10 +615,10 @@ protected void handleStart(final File startDirectory, final Collection result
* The event methods have the prefix {@code handle}.
*
*
- * @param startDirectory the directory to start from, not null
- * @param results the collection of result objects, may be updated
- * @throws NullPointerException if the start directory is null
- * @throws IOException if an I/O Error occurs
+ * @param startDirectory The directory to start from, not null.
+ * @param results The collection of result objects, may be updated.
+ * @throws NullPointerException if the start directory is null.
+ * @throws IOException if an I/O Error occurs.
*/
protected final void walk(final File startDirectory, final Collection results) throws IOException {
Objects.requireNonNull(startDirectory, "startDirectory");
@@ -632,10 +634,10 @@ protected final void walk(final File startDirectory, final Collection results
/**
* Main recursive method to examine the directory hierarchy.
*
- * @param directory the directory to examine, not null
- * @param depth the directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
+ * @param directory The directory to examine, not null.
+ * @param depth The directory level (starting directory = 0).
+ * @param results The collection of result objects, may be updated.
+ * @throws IOException if an I/O Error occurs.
*/
private void walk(final File directory, final int depth, final Collection results) throws IOException {
checkIfCancelled(directory, depth, results);
diff --git a/src/main/java/org/apache/commons/io/EndianUtils.java b/src/main/java/org/apache/commons/io/EndianUtils.java
index 6b4d58eeba3..9765c490e6b 100644
--- a/src/main/java/org/apache/commons/io/EndianUtils.java
+++ b/src/main/java/org/apache/commons/io/EndianUtils.java
@@ -50,9 +50,10 @@ public class EndianUtils {
/**
* Reads the next byte from the input stream.
- * @param input the stream
- * @return the byte
- * @throws IOException if the end of file is reached
+ *
+ * @param input The stream.
+ * @return The byte.
+ * @throws IOException if the end of file is reached.
*/
private static int read(final InputStream input) throws IOException {
final int value = input.read();
@@ -65,10 +66,10 @@ private static int read(final InputStream input) throws IOException {
/**
* Reads a little-endian {@code double} value from a byte array at a given offset.
*
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 8 bytes
+ * @param data source byte array.
+ * @param offset starting offset in the byte array.
+ * @return The value read.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 8 bytes.
*/
public static double readSwappedDouble(final byte[] data, final int offset) {
return Double.longBitsToDouble(readSwappedLong(data, offset));
@@ -77,9 +78,9 @@ public static double readSwappedDouble(final byte[] data, final int offset) {
/**
* Reads a little-endian {@code double} value from an InputStream.
*
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
+ * @param input source InputStream.
+ * @return The value just read.
+ * @throws IOException in case of an I/O problem.
*/
public static double readSwappedDouble(final InputStream input) throws IOException {
return Double.longBitsToDouble(readSwappedLong(input));
@@ -88,10 +89,10 @@ public static double readSwappedDouble(final InputStream input) throws IOExcepti
/**
* Reads a little-endian {@code float} value from a byte array at a given offset.
*
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes
+ * @param data source byte array.
+ * @param offset starting offset in the byte array.
+ * @return The value read.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes.
*/
public static float readSwappedFloat(final byte[] data, final int offset) {
return Float.intBitsToFloat(readSwappedInteger(data, offset));
@@ -100,9 +101,9 @@ public static float readSwappedFloat(final byte[] data, final int offset) {
/**
* Reads a little-endian {@code float} value from an InputStream.
*
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
+ * @param input source InputStream.
+ * @return The value just read.
+ * @throws IOException in case of an I/O problem.
*/
public static float readSwappedFloat(final InputStream input) throws IOException {
return Float.intBitsToFloat(readSwappedInteger(input));
@@ -111,14 +112,15 @@ public static float readSwappedFloat(final InputStream input) throws IOException
/**
* Reads a little-endian {@code int} value from a byte array at a given offset.
*
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes
+ * @param data source byte array.
+ * @param offset starting offset in the byte array.
+ * @return The value read.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes.
*/
public static int readSwappedInteger(final byte[] data, final int offset) {
validateByteArrayOffset(data, offset, Integer.SIZE / Byte.SIZE);
- return ((data[offset + 0] & 0xff) << 0) +
+ return
+ ((data[offset + 0] & 0xff) << 0) +
((data[offset + 1] & 0xff) << 8) +
((data[offset + 2] & 0xff) << 16) +
((data[offset + 3] & 0xff) << 24);
@@ -127,25 +129,29 @@ public static int readSwappedInteger(final byte[] data, final int offset) {
/**
* Reads a little-endian {@code int} value from an InputStream.
*
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
+ * @param input source InputStream.
+ * @return The value just read.
+ * @throws IOException in case of an I/O problem.
*/
public static int readSwappedInteger(final InputStream input) throws IOException {
final int value1 = read(input);
final int value2 = read(input);
final int value3 = read(input);
final int value4 = read(input);
- return ((value1 & 0xff) << 0) + ((value2 & 0xff) << 8) + ((value3 & 0xff) << 16) + ((value4 & 0xff) << 24);
+ return
+ ((value1 & 0xff) << 0) +
+ ((value2 & 0xff) << 8) +
+ ((value3 & 0xff) << 16) +
+ ((value4 & 0xff) << 24);
}
/**
* Reads a little-endian {@code long} value from a byte array at a given offset.
*
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 8 bytes
+ * @param data source byte array.
+ * @param offset starting offset in the byte array.
+ * @return The value read.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 8 bytes.
*/
public static long readSwappedLong(final byte[] data, final int offset) {
validateByteArrayOffset(data, offset, Long.SIZE / Byte.SIZE);
@@ -157,9 +163,9 @@ public static long readSwappedLong(final byte[] data, final int offset) {
/**
* Reads a little-endian {@code long} value from an InputStream.
*
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
+ * @param input source InputStream.
+ * @return The value just read.
+ * @throws IOException in case of an I/O problem.
*/
public static long readSwappedLong(final InputStream input) throws IOException {
final byte[] bytes = new byte[8];
@@ -172,41 +178,47 @@ public static long readSwappedLong(final InputStream input) throws IOException {
/**
* Reads a little-endian {@code short} value from a byte array at a given offset.
*
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 2 bytes
+ * @param data source byte array.
+ * @param offset starting offset in the byte array.
+ * @return The value read.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 2 bytes.
*/
public static short readSwappedShort(final byte[] data, final int offset) {
validateByteArrayOffset(data, offset, Short.SIZE / Byte.SIZE);
- return (short) (((data[offset + 0] & 0xff) << 0) + ((data[offset + 1] & 0xff) << 8));
+ return (short) (
+ ((data[offset + 0] & 0xff) << 0) +
+ ((data[offset + 1] & 0xff) << 8)
+ );
}
/**
* Reads a little-endian {@code short} value from an InputStream.
*
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
+ * @param input source InputStream.
+ * @return The value just read.
+ * @throws IOException in case of an I/O problem.
*/
public static short readSwappedShort(final InputStream input) throws IOException {
- return (short) (((read(input) & 0xff) << 0) + ((read(input) & 0xff) << 8));
+ return (short) (
+ ((read(input) & 0xff) << 0) +
+ ((read(input) & 0xff) << 8)
+ );
}
/**
* Reads a little-endian unsigned integer (32-bit) value from a byte array at a given
* offset.
*
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes
+ * @param data source byte array.
+ * @param offset starting offset in the byte array.
+ * @return The value read.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes.
*/
public static long readSwappedUnsignedInteger(final byte[] data, final int offset) {
validateByteArrayOffset(data, offset, Integer.SIZE / Byte.SIZE);
final long low = ((data[offset + 0] & 0xff) << 0) +
- ((data[offset + 1] & 0xff) << 8) +
- ((data[offset + 2] & 0xff) << 16);
+ ((data[offset + 1] & 0xff) << 8) +
+ ((data[offset + 2] & 0xff) << 16);
final long high = data[offset + 3] & 0xff;
return (high << 24) + (0xffffffffL & low);
}
@@ -214,16 +226,18 @@ public static long readSwappedUnsignedInteger(final byte[] data, final int offse
/**
* Reads a little-endian unsigned integer (32-bit) from an InputStream.
*
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
+ * @param input source InputStream.
+ * @return The value just read.
+ * @throws IOException in case of an I/O problem.
*/
public static long readSwappedUnsignedInteger(final InputStream input) throws IOException {
final int value1 = read(input);
final int value2 = read(input);
final int value3 = read(input);
final int value4 = read(input);
- final long low = ((value1 & 0xff) << 0) + ((value2 & 0xff) << 8) + ((value3 & 0xff) << 16);
+ final long low = ((value1 & 0xff) << 0) +
+ ((value2 & 0xff) << 8) +
+ ((value3 & 0xff) << 16);
final long high = value4 & 0xff;
return (high << 24) + (0xffffffffL & low);
}
@@ -232,28 +246,30 @@ public static long readSwappedUnsignedInteger(final InputStream input) throws IO
* Reads an unsigned short (16-bit) value from a byte array in little-endian order at a given
* offset.
*
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 2 bytes
+ * @param data source byte array.
+ * @param offset starting offset in the byte array.
+ * @return The value read.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 2 bytes.
*/
public static int readSwappedUnsignedShort(final byte[] data, final int offset) {
validateByteArrayOffset(data, offset, Short.SIZE / Byte.SIZE);
- return ((data[offset + 0] & 0xff) << 0) + ((data[offset + 1] & 0xff) << 8);
+ return ((data[offset + 0] & 0xff) << 0) +
+ ((data[offset + 1] & 0xff) << 8);
}
/**
* Reads an unsigned short (16-bit) from an InputStream in little-endian order.
*
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
+ * @param input source InputStream.
+ * @return The value just read.
+ * @throws IOException in case of an I/O problem.
*/
public static int readSwappedUnsignedShort(final InputStream input) throws IOException {
final int value1 = read(input);
final int value2 = read(input);
- return ((value1 & 0xff) << 0) + ((value2 & 0xff) << 8);
+ return ((value1 & 0xff) << 0) +
+ ((value2 & 0xff) << 8);
}
/**
@@ -263,8 +279,8 @@ public static int readSwappedUnsignedShort(final InputStream input) throws IOExc
* This can be useful if you have a number that was read from the
* underlying source in the wrong endianness.
*
- * @param value value to convert
- * @return the converted value
+ * @param value value to convert.
+ * @return The converted value.
*/
public static double swapDouble(final double value) {
return Double.longBitsToDouble(swapLong(Double.doubleToLongBits(value)));
@@ -273,8 +289,8 @@ public static double swapDouble(final double value) {
/**
* Converts a {@code float} value from big-endian to little-endian and vice versa.
*
- * @param value value to convert
- * @return the converted value
+ * @param value value to convert.
+ * @return The converted value.
*/
public static float swapFloat(final float value) {
return Float.intBitsToFloat(swapInteger(Float.floatToIntBits(value)));
@@ -283,8 +299,8 @@ public static float swapFloat(final float value) {
/**
* Converts an {@code int} value from big-endian to little-endian and vice versa.
*
- * @param value value to convert
- * @return the converted value
+ * @param value value to convert.
+ * @return The converted value.
*/
public static int swapInteger(final int value) {
return
@@ -297,8 +313,8 @@ public static int swapInteger(final int value) {
/**
* Converts a {@code long} value from big-endian to little-endian and vice versa.
*
- * @param value value to convert
- * @return the converted value
+ * @param value value to convert.
+ * @return The converted value.
*/
public static long swapLong(final long value) {
return
@@ -315,21 +331,23 @@ public static long swapLong(final long value) {
/**
* Converts a {@code short} value from big-endian to little-endian and vice versa.
*
- * @param value value to convert
- * @return the converted value
+ * @param value value to convert.
+ * @return The converted value.
*/
public static short swapShort(final short value) {
- return (short) (((value >> 0 & 0xff) << 8) +
- ((value >> 8 & 0xff) << 0));
+ return (short) (
+ ((value >> 0 & 0xff) << 8) +
+ ((value >> 8 & 0xff) << 0)
+ );
}
/**
* Validates if the provided byte array has enough data.
*
- * @param data the input byte array
- * @param offset the input offset
- * @param byteNeeded the needed number of bytes
- * @throws IllegalArgumentException if the byte array does not have enough data
+ * @param data The input byte array.
+ * @param offset The input offset.
+ * @param byteNeeded The needed number of bytes.
+ * @throws IllegalArgumentException if the byte array does not have enough data.
*/
private static void validateByteArrayOffset(final byte[] data, final int offset, final int byteNeeded) {
if (data.length < offset + byteNeeded) {
@@ -340,10 +358,10 @@ private static void validateByteArrayOffset(final byte[] data, final int offset,
/**
* Writes the 8 bytes of a {@code double} to a byte array at a given offset in little-endian order.
*
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 8 bytes
+ * @param data target byte array.
+ * @param offset starting offset in the byte array.
+ * @param value value to write.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 8 bytes.
*/
public static void writeSwappedDouble(final byte[] data, final int offset, final double value) {
writeSwappedLong(data, offset, Double.doubleToLongBits(value));
@@ -352,9 +370,9 @@ public static void writeSwappedDouble(final byte[] data, final int offset, final
/**
* Writes the 8 bytes of a {@code double} to an output stream in little-endian order.
*
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
+ * @param output target OutputStream.
+ * @param value value to write.
+ * @throws IOException in case of an I/O problem.
*/
public static void writeSwappedDouble(final OutputStream output, final double value) throws IOException {
writeSwappedLong(output, Double.doubleToLongBits(value));
@@ -363,10 +381,10 @@ public static void writeSwappedDouble(final OutputStream output, final double va
/**
* Writes the 4 bytes of a {@code float} to a byte array at a given offset in little-endian order.
*
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes
+ * @param data target byte array.
+ * @param offset starting offset in the byte array.
+ * @param value value to write.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes.
*/
public static void writeSwappedFloat(final byte[] data, final int offset, final float value) {
writeSwappedInteger(data, offset, Float.floatToIntBits(value));
@@ -375,9 +393,9 @@ public static void writeSwappedFloat(final byte[] data, final int offset, final
/**
* Writes the 4 bytes of a {@code float} to an output stream in little-endian order.
*
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
+ * @param output target OutputStream.
+ * @param value value to write.
+ * @throws IOException in case of an I/O problem.
*/
public static void writeSwappedFloat(final OutputStream output, final float value) throws IOException {
writeSwappedInteger(output, Float.floatToIntBits(value));
@@ -386,10 +404,10 @@ public static void writeSwappedFloat(final OutputStream output, final float valu
/**
* Writes the 4 bytes of an {@code int} to a byte array at a given offset in little-endian order.
*
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes
+ * @param data target byte array.
+ * @param offset starting offset in the byte array.
+ * @param value value to write.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 4 bytes.
*/
public static void writeSwappedInteger(final byte[] data, final int offset, final int value) {
validateByteArrayOffset(data, offset, Integer.SIZE / Byte.SIZE);
@@ -402,9 +420,9 @@ public static void writeSwappedInteger(final byte[] data, final int offset, fina
/**
* Writes the 4 bytes of an {@code int} to an output stream in little-endian order.
*
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
+ * @param output target OutputStream.
+ * @param value value to write.
+ * @throws IOException in case of an I/O problem.
*/
public static void writeSwappedInteger(final OutputStream output, final int value) throws IOException {
output.write((byte) (value >> 0 & 0xff));
@@ -416,10 +434,10 @@ public static void writeSwappedInteger(final OutputStream output, final int valu
/**
* Writes the 8 bytes of a {@code long} to a byte array at a given offset in little-endian order.
*
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 8 bytes
+ * @param data target byte array.
+ * @param offset starting offset in the byte array.
+ * @param value value to write.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 8 bytes.
*/
public static void writeSwappedLong(final byte[] data, final int offset, final long value) {
validateByteArrayOffset(data, offset, Long.SIZE / Byte.SIZE);
@@ -436,9 +454,9 @@ public static void writeSwappedLong(final byte[] data, final int offset, final l
/**
* Writes the 8 bytes of a {@code long} to an output stream in little-endian order.
*
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
+ * @param output target OutputStream.
+ * @param value value to write.
+ * @throws IOException in case of an I/O problem.
*/
public static void writeSwappedLong(final OutputStream output, final long value) throws IOException {
output.write((byte) (value >> 0 & 0xff));
@@ -454,10 +472,10 @@ public static void writeSwappedLong(final OutputStream output, final long value)
/**
* Writes the 2 bytes of a {@code short} to a byte array at a given offset in little-endian order.
*
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 2 bytes
+ * @param data target byte array.
+ * @param offset starting offset in the byte array.
+ * @param value value to write.
+ * @throws IllegalArgumentException if the part of the byte array starting at offset does not have at least 2 bytes.
*/
public static void writeSwappedShort(final byte[] data, final int offset, final short value) {
validateByteArrayOffset(data, offset, Short.SIZE / Byte.SIZE);
@@ -468,9 +486,9 @@ public static void writeSwappedShort(final byte[] data, final int offset, final
/**
* Writes the 2 bytes of a {@code short} to an output stream using little-endian encoding.
*
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
+ * @param output target OutputStream.
+ * @param value value to write.
+ * @throws IOException in case of an I/O problem.
*/
public static void writeSwappedShort(final OutputStream output, final short value) throws IOException {
output.write((byte) (value >> 0 & 0xff));
diff --git a/src/main/java/org/apache/commons/io/FileCleaner.java b/src/main/java/org/apache/commons/io/FileCleaner.java
index 5ffdd7db219..09b2dd34138 100644
--- a/src/main/java/org/apache/commons/io/FileCleaner.java
+++ b/src/main/java/org/apache/commons/io/FileCleaner.java
@@ -25,12 +25,14 @@
* This utility creates a background thread to handle file deletion.
* Each file to be deleted is registered with a handler object.
* When the handler object is garbage collected, the file is deleted.
+ *
*
* In an environment with multiple class loaders (a servlet container, for
* example), you should consider stopping the background thread if it is no
* longer needed. This is done by invoking the method
* {@link #exitWhenFinished}, typically in
* {@code javax.servlet.ServletContextListener.contextDestroyed(javax.servlet.ServletContextEvent)} or similar.
+ *
*
* @deprecated Use {@link FileCleaningTracker}
*/
@@ -51,18 +53,22 @@ public class FileCleaner {
* with multiple class loaders (such as an application server), you should be
* aware that the file cleaner thread will continue running even if the class
* loader it was started from terminates. This can constitute a memory leak.
+ *
*
* For example, suppose that you have developed a web application, which
- * contains the commons-io jar file in your WEB-INF/lib directory. In other
+ * contains the Commons IO jar file in your WEB-INF/lib directory. In other
* words, the FileCleaner class is loaded through the class loader of your
* web application. If the web application is terminated, but the servlet
* container is still running, then the file cleaner thread will still exist,
* posing a memory leak.
+ *
*
* This method allows the thread to be terminated. Simply call this method
* in the resource cleanup code, such as
* {@code javax.servlet.ServletContextListener.contextDestroyed(javax.servlet.ServletContextEvent)}.
* One called, no new objects can be tracked by the file cleaner.
+ *
+ *
* @deprecated Use {@link FileCleaningTracker#exitWhenFinished()}.
*/
@Deprecated
@@ -76,7 +82,7 @@ public static synchronized void exitWhenFinished() {
* {@link FileCleaningTracker} class while maintain compatibility with the
* deprecated {@link FileCleaner}.
*
- * @return the singleton instance
+ * @return The singleton instance.
*/
public static FileCleaningTracker getInstance() {
return INSTANCE;
@@ -86,7 +92,7 @@ public static FileCleaningTracker getInstance() {
* Gets the number of files currently being tracked, and therefore
* awaiting deletion.
*
- * @return the number of files being tracked
+ * @return The number of files being tracked.
* @deprecated Use {@link FileCleaningTracker#getTrackCount()}.
*/
@Deprecated
@@ -99,9 +105,9 @@ public static int getTrackCount() {
* when the marker instance is garbage collected.
* The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
*
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @throws NullPointerException if the file is null
+ * @param file The file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @throws NullPointerException if the file is null.
* @deprecated Use {@link FileCleaningTracker#track(File, Object)}.
*/
@Deprecated
@@ -114,10 +120,10 @@ public static void track(final File file, final Object marker) {
* when the marker instance is garbage collected.
* The specified deletion strategy is used.
*
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @throws NullPointerException if the file is null
+ * @param file The file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @param deleteStrategy The strategy to delete the file, null means normal.
+ * @throws NullPointerException if the file is null.
* @deprecated Use {@link FileCleaningTracker#track(File, Object, FileDeleteStrategy)}.
*/
@Deprecated
@@ -130,9 +136,9 @@ public static void track(final File file, final Object marker, final FileDeleteS
* when the marker instance is garbage collected.
* The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
*
- * @param path the full path to the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @throws NullPointerException if the path is null
+ * @param path The full path to the file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @throws NullPointerException if the path is null.
* @deprecated Use {@link FileCleaningTracker#track(String, Object)}.
*/
@Deprecated
@@ -145,10 +151,10 @@ public static void track(final String path, final Object marker) {
* when the marker instance is garbage collected.
* The specified deletion strategy is used.
*
- * @param path the full path to the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @throws NullPointerException if the path is null
+ * @param path The full path to the file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @param deleteStrategy The strategy to delete the file, null means normal.
+ * @throws NullPointerException if the path is null.
* @deprecated Use {@link FileCleaningTracker#track(String, Object, FileDeleteStrategy)}.
*/
@Deprecated
diff --git a/src/main/java/org/apache/commons/io/FileCleaningTracker.java b/src/main/java/org/apache/commons/io/FileCleaningTracker.java
index 98edebc518e..376f5d636cb 100644
--- a/src/main/java/org/apache/commons/io/FileCleaningTracker.java
+++ b/src/main/java/org/apache/commons/io/FileCleaningTracker.java
@@ -21,14 +21,14 @@
import java.lang.ref.ReferenceQueue;
import java.nio.file.Path;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
+import java.util.Set;
/**
- * Keeps track of files awaiting deletion, and deletes them when an associated
+ * Tracks files awaiting deletion, and deletes them when an associated
* marker object is reclaimed by the garbage collector.
*
* This utility creates a background thread to handle file deletion.
@@ -51,9 +51,10 @@ public class FileCleaningTracker {
* The reaper thread.
*/
private final class Reaper extends Thread {
+
/** Constructs a new Reaper */
Reaper() {
- super("File Reaper");
+ super("commons-io-FileCleaningTracker-Reaper");
setPriority(MAX_PRIORITY);
setDaemon(true);
}
@@ -65,16 +66,18 @@ private final class Reaper extends Thread {
@Override
public void run() {
// thread exits when exitWhenFinished is true and there are no more tracked objects
- while (!exitWhenFinished || !trackers.isEmpty()) {
+ while (!(exitWhenFinished && trackers.isEmpty())) {
try {
// Wait for a tracker to remove.
- final Tracker tracker = (Tracker) q.remove(); // cannot return null
+ final Tracker tracker = (Tracker) refQueue.remove(); // cannot return null
trackers.remove(tracker);
if (!tracker.delete()) {
deleteFailures.add(tracker.getPath());
}
tracker.clear();
} catch (final InterruptedException e) {
+ // interrupted removing from the queue.
+ interrupt();
continue;
}
}
@@ -99,15 +102,14 @@ private static final class Tracker extends PhantomReference
*
* For example, suppose that you have developed a web application, which
- * contains the commons-io jar file in your WEB-INF/lib directory. In other
+ * contains the Commons IO JAR file in your WEB-INF/lib directory. In other
* words, the FileCleaner class is loaded through the class loader of your
* web application. If the web application is terminated, but the servlet
* container is still running, then the file cleaner thread will still exist,
* posing a memory leak.
+ *
*
* This method allows the thread to be terminated. Simply call this method
* in the resource cleanup code, such as
* {@code javax.servlet.ServletContextListener.contextDestroyed(javax.servlet.ServletContextEvent)}.
* Once called, no new objects can be tracked by the file cleaner.
+ *
*/
public synchronized void exitWhenFinished() {
- // synchronized block protects reaper
+ // synchronized method guards reaper
exitWhenFinished = true;
if (reaper != null) {
synchronized (reaper) {
@@ -218,7 +223,7 @@ public synchronized void exitWhenFinished() {
/**
* Gets a copy of the file paths that failed to delete.
*
- * @return a copy of the file paths that failed to delete
+ * @return A copy of the file paths that failed to delete.
* @since 2.0
*/
public List getDeleteFailures() {
@@ -229,7 +234,7 @@ public List getDeleteFailures() {
* Gets the number of files currently being tracked, and therefore
* awaiting deletion.
*
- * @return the number of files being tracked
+ * @return The number of files being tracked.
*/
public int getTrackCount() {
return trackers.size();
@@ -240,9 +245,9 @@ public int getTrackCount() {
* when the marker instance is garbage collected.
* The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
*
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @throws NullPointerException if the file is null
+ * @param file The file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @throws NullPointerException if the file is null.
*/
public void track(final File file, final Object marker) {
track(file, marker, null);
@@ -253,10 +258,10 @@ public void track(final File file, final Object marker) {
* when the marker instance is garbage collected.
* The specified deletion strategy is used.
*
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @throws NullPointerException if the file is null
+ * @param file The file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @param deleteStrategy The strategy to delete the file, null means normal.
+ * @throws NullPointerException if the file is null.
*/
public void track(final File file, final Object marker, final FileDeleteStrategy deleteStrategy) {
Objects.requireNonNull(file, "file");
@@ -268,9 +273,9 @@ public void track(final File file, final Object marker, final FileDeleteStrategy
* when the marker instance is garbage collected.
* The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
*
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @throws NullPointerException if the file is null
+ * @param file The file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @throws NullPointerException if the file is null.
* @since 2.14.0
*/
public void track(final Path file, final Object marker) {
@@ -282,10 +287,10 @@ public void track(final Path file, final Object marker) {
* when the marker instance is garbage collected.
* The specified deletion strategy is used.
*
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @throws NullPointerException if the file is null
+ * @param file The file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @param deleteStrategy The strategy to delete the file, null means normal.
+ * @throws NullPointerException if the file is null.
* @since 2.14.0
*/
public void track(final Path file, final Object marker, final FileDeleteStrategy deleteStrategy) {
@@ -298,9 +303,9 @@ public void track(final Path file, final Object marker, final FileDeleteStrategy
* when the marker instance is garbage collected.
* The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
*
- * @param path the full path to the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @throws NullPointerException if the path is null
+ * @param path The full path to the file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @throws NullPointerException if the path is null.
*/
public void track(final String path, final Object marker) {
track(path, marker, null);
@@ -311,13 +316,12 @@ public void track(final String path, final Object marker) {
* when the marker instance is garbage collected.
* The specified deletion strategy is used.
*
- * @param path the full path to the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @throws NullPointerException if the path is null
+ * @param path The full path to the file to be tracked, not null.
+ * @param marker The marker object used to track the file, not null.
+ * @param deleteStrategy The strategy to delete the file, null means normal.
+ * @throws NullPointerException Thrown if the path is null.
*/
public void track(final String path, final Object marker, final FileDeleteStrategy deleteStrategy) {
- Objects.requireNonNull(path, "path");
addTracker(path, marker, deleteStrategy);
}
diff --git a/src/main/java/org/apache/commons/io/FileDeleteStrategy.java b/src/main/java/org/apache/commons/io/FileDeleteStrategy.java
index 62cf28c1631..2d1afc4bdcb 100644
--- a/src/main/java/org/apache/commons/io/FileDeleteStrategy.java
+++ b/src/main/java/org/apache/commons/io/FileDeleteStrategy.java
@@ -37,7 +37,7 @@ public class FileDeleteStrategy {
/**
* Force file deletion strategy.
*/
- static class ForceFileDeleteStrategy extends FileDeleteStrategy {
+ static final class ForceFileDeleteStrategy extends FileDeleteStrategy {
/** Default Constructor */
ForceFileDeleteStrategy() {
@@ -51,10 +51,10 @@ static class ForceFileDeleteStrategy extends FileDeleteStrategy {
* if the file exists.
*
*
- * @param fileToDelete the file to delete, not null
+ * @param fileToDelete The file to delete, not null.
* @return Always returns {@code true}
- * @throws NullPointerException if the file is null
- * @throws IOException if an error occurs during file deletion
+ * @throws NullPointerException if the file is null.
+ * @throws IOException if an error occurs during file deletion.
*/
@Override
protected boolean doDelete(final File fileToDelete) throws IOException {
@@ -81,7 +81,7 @@ protected boolean doDelete(final File fileToDelete) throws IOException {
/**
* Restricted constructor.
*
- * @param name the name by which the strategy is known
+ * @param name The name by which the strategy is known.
*/
protected FileDeleteStrategy(final String name) {
this.name = name;
@@ -94,9 +94,9 @@ protected FileDeleteStrategy(final String name) {
* Subclass writers should override {@link #doDelete(File)}, not this method.
*
*
- * @param fileToDelete the file to delete, not null
- * @throws NullPointerException if the file is null
- * @throws IOException if an error occurs during file deletion
+ * @param fileToDelete The file to delete, not null.
+ * @throws NullPointerException if the file is null.
+ * @throws IOException if an error occurs during file deletion.
*/
public void delete(final File fileToDelete) throws IOException {
if (fileToDelete.exists() && !doDelete(fileToDelete)) {
@@ -112,8 +112,8 @@ public void delete(final File fileToDelete) throws IOException {
* Subclass writers should override {@link #doDelete(File)}, not this method.
*
*
- * @param fileToDelete the file to delete, null returns true
- * @return true if the file was deleted, or there was no such file
+ * @param fileToDelete The file to delete, null returns true.
+ * @return true if the file was deleted, or there was no such file.
*/
public boolean deleteQuietly(final File fileToDelete) {
if (fileToDelete == null || !fileToDelete.exists()) {
@@ -139,10 +139,10 @@ public boolean deleteQuietly(final File fileToDelete) {
* This implementation uses {@link FileUtils#delete(File)}.
*
*
- * @param file the file to delete, exists, not null
- * @return true if the file was deleted
- * @throws NullPointerException if the file is null
- * @throws IOException if an error occurs during file deletion
+ * @param file The file to delete, exists, not null.
+ * @return true if the file was deleted.
+ * @throws NullPointerException if the file is null.
+ * @throws IOException if an error occurs during file deletion.
*/
protected boolean doDelete(final File file) throws IOException {
FileUtils.delete(file);
@@ -152,7 +152,7 @@ protected boolean doDelete(final File file) throws IOException {
/**
* Gets a string describing the delete strategy.
*
- * @return a string describing the delete strategy
+ * @return A string describing the delete strategy.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/FileExistsException.java b/src/main/java/org/apache/commons/io/FileExistsException.java
index 1f733cf11ae..0b18ff8cac2 100644
--- a/src/main/java/org/apache/commons/io/FileExistsException.java
+++ b/src/main/java/org/apache/commons/io/FileExistsException.java
@@ -20,7 +20,7 @@
import java.io.IOException;
/**
- * Indicates that a file already exists.
+ * Signals that a file already exists.
*
* @since 2.0
*/
@@ -40,7 +40,7 @@ public FileExistsException() {
/**
* Constructs an instance with the specified file.
*
- * @param file The file that exists
+ * @param file The file that exists.
*/
public FileExistsException(final File file) {
super("File " + file + " exists");
@@ -49,7 +49,7 @@ public FileExistsException(final File file) {
/**
* Constructs an instance with the specified message.
*
- * @param message The error message
+ * @param message The error message.
*/
public FileExistsException(final String message) {
super(message);
diff --git a/src/main/java/org/apache/commons/io/FileSystem.java b/src/main/java/org/apache/commons/io/FileSystem.java
index 4169e1a53b1..7d332046625 100644
--- a/src/main/java/org/apache/commons/io/FileSystem.java
+++ b/src/main/java/org/apache/commons/io/FileSystem.java
@@ -32,11 +32,10 @@
import java.util.Objects;
/**
- * Abstracts an OS' file system details, currently supporting the single use case of converting a file name String to a
- * legal file name with {@link #toLegalFileName(String, char)}.
+ * Enumerates file system details for operating systems, currently supporting the single use case of converting a file name String to a legal file name with
+ * {@link #toLegalFileName(String, char)}.
*
- * The starting point of any operation is {@link #getCurrent()} which gets you the enum for the file system that matches
- * the OS hosting the running JVM.
+ * The starting point of any operation is {@link #getCurrent()} which gets you the enum for the file system that matches the OS hosting the running JVM.
*
*
* @since 2.7
@@ -118,6 +117,7 @@ public enum FileSystem {
* Implementations measure length and can truncate to a specified limit.
*/
enum NameLengthStrategy {
+
/** Length measured as encoded bytes. */
BYTES {
@Override
@@ -266,7 +266,7 @@ final boolean isWithinLimit(final CharSequence value, final int limit, final Cha
/**
* Gets the current file system.
*
- * @return the current file system
+ * @return The current file system.
*/
private static FileSystem current() {
if (IS_OS_LINUX) {
@@ -284,7 +284,7 @@ private static FileSystem current() {
/**
* Gets the current file system.
*
- * @return the current file system
+ * @return The current file system.
*/
public static FileSystem getCurrent() {
return CURRENT;
@@ -294,8 +294,8 @@ public static FileSystem getCurrent() {
* Decides if the operating system matches.
*
* @param osNamePrefix
- * the prefix for the os name
- * @return true if matches, or false if not or can't determine
+ * the prefix for the operating system name.
+ * @return true if matches, or false if not or can't determine.
*/
private static boolean getOsMatchesName(final String osNamePrefix) {
return isOsNameMatch(getSystemProperty("os.name"), osNamePrefix);
@@ -309,8 +309,8 @@ private static boolean getOsMatchesName(final String osNamePrefix) {
*
*
* @param property
- * the system property name
- * @return the system property value or {@code null} if a security problem occurs
+ * the system property name.
+ * @return The system property value or {@code null} if a security problem occurs.
*/
private static String getSystemProperty(final String property) {
try {
@@ -345,10 +345,10 @@ private static int indexOfFirstDot(final CharSequence cs) {
*
*
* @param osName
- * the actual OS name
+ * the actual OS name.
* @param osNamePrefix
- * the prefix for the expected OS name
- * @return true if matches, or false if not or can't determine
+ * the prefix for the expected OS name.
+ * @return true if matches, or false if not or can't determine.
*/
private static boolean isOsNameMatch(final String osName, final String osNamePrefix) {
if (osName == null) {
@@ -360,10 +360,10 @@ private static boolean isOsNameMatch(final String osName, final String osNamePre
/**
* Null-safe replace.
*
- * @param path the path to be changed, null ignored.
- * @param oldChar the old character.
- * @param newChar the new character.
- * @return the new path.
+ * @param path The path to be changed, null ignored.
+ * @param oldChar The old character.
+ * @param newChar The new character.
+ * @return The new path.
*/
private static String replace(final String path, final char oldChar, final char newChar) {
return path == null ? null : path.replace(oldChar, newChar);
@@ -459,7 +459,7 @@ static CharSequence trimExtension(final CharSequence cs) {
/**
* Gets the file allocation block size in bytes.
*
- * @return the file allocation block size in bytes.
+ * @return The file allocation block size in bytes.
* @since 2.12.0
*/
public int getBlockSize() {
@@ -469,7 +469,7 @@ public int getBlockSize() {
/**
* Gets a cloned copy of the illegal characters for this file system.
*
- * @return the illegal characters for this file system.
+ * @return The illegal characters for this file system.
*/
public char[] getIllegalFileNameChars() {
final char[] chars = new char[illegalFileNameChars.length];
@@ -482,7 +482,7 @@ public char[] getIllegalFileNameChars() {
/**
* Gets a cloned copy of the illegal code points for this file system.
*
- * @return the illegal code points for this file system.
+ * @return The illegal code points for this file system.
* @since 2.12.0
*/
public int[] getIllegalFileNameCodePoints() {
@@ -513,7 +513,7 @@ public int[] getIllegalFileNameCodePoints() {
* However, any file name longer than this limit is guaranteed to be invalid on the current file system.
*
*
- * @return the maximum file name length in characters.
+ * @return The maximum file name length in characters.
*/
public int getMaxFileNameLength() {
return maxFileNameLength;
@@ -540,7 +540,7 @@ public int getMaxFileNameLength() {
* Conversely, any path longer than this limit is guaranteed to fail with at least some operating system API calls.
*
*
- * @return the maximum file path length in characters.
+ * @return The maximum file path length in characters.
*/
public int getMaxPathLength() {
return maxPathLength;
@@ -563,7 +563,7 @@ public char getNameSeparator() {
/**
* Gets a cloned copy of the reserved file names.
*
- * @return the reserved file names.
+ * @return The reserved file names.
*/
public String[] getReservedFileNames() {
return reservedFileNames.clone();
@@ -656,8 +656,8 @@ public boolean isReservedFileName(final CharSequence candidate) {
/**
* Converts all separators to the Windows separator of backslash.
*
- * @param path the path to be changed, null ignored.
- * @return the updated path.
+ * @param path The path to be changed, null ignored.
+ * @return The updated path.
* @since 2.12.0
*/
public String normalizeSeparators(final String path) {
@@ -695,7 +695,7 @@ public boolean supportsDriveLetter() {
* Illegal characters in the candidate name are replaced by this character.
* @param charset
* The charset to use when the file name length is measured in bytes.
- * @return a String without illegal characters.
+ * @return A String without illegal characters.
* @since 2.21.0
*/
public String toLegalFileName(final CharSequence candidate, final char replacement, final Charset charset) {
@@ -727,7 +727,7 @@ public String toLegalFileName(final CharSequence candidate, final char replaceme
* A candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"}.
* @param replacement
* Illegal characters in the candidate name are replaced by this character.
- * @return a String without illegal characters.
+ * @return A String without illegal characters.
*/
public String toLegalFileName(final String candidate, final char replacement) {
return toLegalFileName(candidate, replacement, Charset.defaultCharset());
diff --git a/src/main/java/org/apache/commons/io/FileSystemUtils.java b/src/main/java/org/apache/commons/io/FileSystemUtils.java
index 4c0af0d3671..bc0d43257f4 100644
--- a/src/main/java/org/apache/commons/io/FileSystemUtils.java
+++ b/src/main/java/org/apache/commons/io/FileSystemUtils.java
@@ -53,12 +53,12 @@ public class FileSystemUtils {
* FileSystemUtils.freeSpace("/volume"); // *nix
*
*
- * @param path the path to get free space for, not null, not empty on Unix
- * @return the amount of free drive space on the drive or volume
+ * @param path The path to get free space for, not null, not empty on Unix.
+ * @return The amount of free drive space on the drive or volume.
* @throws IOException if an I/O error occurs.
* @throws IllegalArgumentException if the path is invalid.
* @since 1.1, enhanced OS support in 1.2 and 1.3
- * @deprecated Use freeSpaceKb(String) Deprecated from 1.3, may be removed in 2.0
+ * @deprecated Use freeSpaceKb(String) Deprecated from 1.3, may be removed in 2.0.
*/
@Deprecated
public static long freeSpace(final String path) throws IOException {
@@ -75,7 +75,7 @@ public static long freeSpace(final String path) throws IOException {
* freeSpaceKb(FileUtils.current().getAbsolutePath())
*
*
- * @return the amount of free drive space on the drive or volume in kilobytes
+ * @return The amount of free drive space on the drive or volume in kilobytes.
* @throws IOException if an I/O error occurs.
* @throws IllegalArgumentException if the path is invalid.
* @since 2.0
@@ -97,7 +97,7 @@ public static long freeSpaceKb() throws IOException {
*
*
* @param timeout ignored.
- * @return the amount of free drive space on the drive or volume in kilobytes
+ * @return The amount of free drive space on the drive or volume in kilobytes.
* @throws IOException if an I/O error occurs.
* @throws IllegalArgumentException if the path is invalid.
* @since 2.0
@@ -116,8 +116,8 @@ public static long freeSpaceKb(final long timeout) throws IOException {
* FileSystemUtils.freeSpaceKb("/volume"); // *nix
*
*
- * @param path the path to get free space for, not null, not empty on Unix
- * @return the amount of free drive space on the drive or volume in kilobytes
+ * @param path The path to get free space for, not null, not empty on Unix.
+ * @return The amount of free drive space on the drive or volume in kilobytes.
* @throws IOException if an I/O error occurs.
* @throws IllegalArgumentException if the path is invalid.
* @since 1.2, enhanced OS support in 1.3
@@ -136,9 +136,9 @@ public static long freeSpaceKb(final String path) throws IOException {
* FileSystemUtils.freeSpaceKb("/volume"); // *nix
*
*
- * @param path the path to get free space for, not null, not empty on Unix
+ * @param path The path to get free space for, not null, not empty on Unix.
* @param timeout ignored.
- * @return the amount of free drive space on the drive or volume in kilobytes
+ * @return The amount of free drive space on the drive or volume in kilobytes.
* @throws IOException if an I/O error occurs.
* @throws IllegalArgumentException if the path is invalid.
* @since 2.0
@@ -157,8 +157,8 @@ public static long freeSpaceKb(final String path, final long timeout) throws IOE
* FileSystemUtils.freeSpace("/volume"); // *nix
*
*
- * @param pathStr the path to get free space for, not null, not empty on Unix
- * @return the amount of free drive space on the drive or volume
+ * @param pathStr The path to get free space for, not null, not empty on Unix.
+ * @return The amount of free drive space on the drive or volume.
* @throws IOException if an I/O error occurs.
* @throws IllegalArgumentException if the path is invalid.
*/
diff --git a/src/main/java/org/apache/commons/io/FileUtils.java b/src/main/java/org/apache/commons/io/FileUtils.java
index 203fe84bfc5..43349e835f1 100644
--- a/src/main/java/org/apache/commons/io/FileUtils.java
+++ b/src/main/java/org/apache/commons/io/FileUtils.java
@@ -93,16 +93,16 @@
* Facilities are provided in the following areas:
*
*
- *
writing to a file
- *
reading from a file
- *
make a directory including parent directories
- *
copying files and directories
- *
deleting files and directories
- *
converting to and from a URL
- *
listing files and directories by filter and extension
- *
comparing file content
- *
file last changed date
- *
calculating a checksum
+ *
writing to a file
+ *
reading from a file
+ *
make a directory including parent directories
+ *
copying files and directories
+ *
deleting files and directories
+ *
converting to and from a URL
+ *
listing files and directories by filter and extension
+ *
comparing file content
+ *
file last changed date
+ *
calculating a checksum
*
*
* Note that a specific charset should be specified whenever possible. Relying on the platform default means that the
@@ -112,7 +112,7 @@
* {@link SecurityException} are not documented in the Javadoc.
*
*/
public class FileUtils {
@@ -230,8 +230,8 @@ public class FileUtils {
* Similarly for the 1MB and 1KB boundaries.
*
*
- * @param size the number of bytes
- * @return a human-readable display value (includes units - QB, RB, YB, ZB, EB, PB, TB, GB, MB, KB or bytes)
+ * @param size The number of bytes.
+ * @return A human-readable display value (includes units - QB, RB, YB, ZB, EB, PB, TB, GB, MB, KB or bytes).
* @throws NullPointerException if the given {@link BigInteger} is {@code null}.
* @see IO-226 - should the rounding be changed?
* @since 2.4
@@ -276,8 +276,8 @@ public static String byteCountToDisplaySize(final BigInteger size) {
* Similarly for the 1MB and 1KB boundaries.
*
*
- * @param size the number of bytes
- * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
+ * @param size The number of bytes.
+ * @return A human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes).
* @see IO-226 - should the rounding be changed?
*/
// See https://issues.apache.org/jira/browse/IO-226 - should the rounding be changed?
@@ -295,8 +295,8 @@ public static String byteCountToDisplaySize(final long size) {
* Similarly for the 1MB and 1KB boundaries.
*
*
- * @param size the number of bytes
- * @return a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
+ * @param size The number of bytes.
+ * @return A human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes).
* @see IO-226 - should the rounding be changed?
* @since 2.12.0
*/
@@ -355,13 +355,13 @@ private static File checkIsFile(final File file, final String name) {
* long checksum = FileUtils.checksum(file, new CRC32()).getValue();
*
*
- * @param file the file to checksum, must not be {@code null}
- * @param checksum the checksum object to be used, must not be {@code null}
- * @return the checksum specified, updated with the content of the file
+ * @param file The file to checksum, must not be {@code null}
+ * @param checksum The checksum object to be used, must not be {@code null}
+ * @return The checksum specified, updated with the content of the file.
* @throws NullPointerException if the given {@link File} is {@code null}.
* @throws NullPointerException if the given {@link Checksum} is {@code null}.
* @throws IllegalArgumentException if the given {@link File} is not a file.
- * @throws FileNotFoundException if the file does not exist
+ * @throws FileNotFoundException if the file does not exist.
* @throws IOException if an IO error occurs reading the file.
* @since 1.3
*/
@@ -378,8 +378,8 @@ public static Checksum checksum(final File file, final Checksum checksum) throws
* Computes the checksum of a file using the CRC32 checksum routine.
* The value of the checksum is returned.
*
- * @param file the file to checksum, must not be {@code null}
- * @return the checksum value
+ * @param file The file to checksum, must not be {@code null}
+ * @return The checksum value.
* @throws NullPointerException if the {@code file} is {@code null}.
* @throws IllegalArgumentException if the {@code file} does not exist or is not a file.
* @throws IOException if an IO error occurs reading the file.
@@ -392,7 +392,7 @@ public static long checksumCRC32(final File file) throws IOException {
/**
* Cleans a directory without deleting it.
*
- * @param directory directory to clean
+ * @param directory directory to clean.
* @throws NullPointerException if the given {@link File} is {@code null}.
* @throws IllegalArgumentException if the {@code directory} does not exist or is not a directory.
* @throws IOException if an I/O error occurs.
@@ -422,9 +422,9 @@ private static void cleanDirectoryOnExit(final File directory) throws IOExceptio
* resorting to byte-by-byte comparison of the contents.
*
*
- * @param file1 the first file
- * @param file2 the second file
- * @return true if the content of the files are equal or they both don't exist, false otherwise
+ * @param file1 The first file.
+ * @param file2 The second file.
+ * @return true if the content of the files are equal or they both don't exist, false otherwise.
* @throws IllegalArgumentException when an input is not a file.
* @throws IOException If an I/O error occurs.
* @see PathUtils#fileContentEquals(Path,Path)
@@ -464,12 +464,12 @@ public static boolean contentEquals(final File file1, final File file2) throws I
* before resorting to line-by-line comparison of the contents.
*
*
- * @param file1 the first file
- * @param file2 the second file
- * @param charsetName the name of the requested charset.
- * May be null, in which case the platform default is used
+ * @param file1 The first file.
+ * @param file2 The second file.
+ * @param charsetName The name of the requested charset.
+ * May be null, in which case the platform default is used.
* @return true if the content of the files are equal or neither exists,
- * false otherwise
+ * false otherwise.
* @throws IllegalArgumentException when an input is not a file.
* @throws IOException in case of an I/O error.
* @throws UnsupportedCharsetException If the named charset is unavailable (unchecked exception).
@@ -509,8 +509,8 @@ public static boolean contentEqualsIgnoreEOL(final File file1, final File file2,
* representation. This is to account for the difference between
* File.listFiles() and FileUtils.listFiles().
*
- * @param files a Collection containing {@link File} instances
- * @return an array of {@link File}
+ * @param files A Collection containing {@link File} instances.
+ * @return An array of {@link File}
*/
public static File[] convertFileCollectionToFileArray(final Collection files) {
return files.toArray(EMPTY_FILE_ARRAY);
@@ -541,13 +541,13 @@ public static File[] convertFileCollectionToFileArray(final Collection fil
* newly created copy of the target.
*
*
- * @param srcDir an existing directory to copy, must not be {@code null}.
- * @param destDir the new directory, must not be {@code null}.
+ * @param srcDir An existing directory to copy, must not be {@code null}.
+ * @param destDir The new directory, must not be {@code null}.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IllegalArgumentException if {@code srcDir} exists but is not a directory,
- * the source and the destination directory are the same
+ * the source and the destination directory are the same.
* @throws FileNotFoundException if the source does not exist.
- * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
+ * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed.
* @since 1.1
*/
public static void copyDirectory(final File srcDir, final File destDir) throws IOException {
@@ -569,13 +569,13 @@ public static void copyDirectory(final File srcDir, final File destDir) throws I
* will succeed. If the modification operation fails, the method throws IOException.
*
*
- * @param srcDir an existing directory to copy, must not be {@code null}.
- * @param destDir the new directory, must not be {@code null}.
+ * @param srcDir An existing directory to copy, must not be {@code null}.
+ * @param destDir The new directory, must not be {@code null}.
* @param preserveFileDate true if the file date of the copy should be the same as the original.
* @throws IllegalArgumentException if {@code srcDir} exists but is not a directory, or
- * the source and the destination directory are the same
+ * the source and the destination directory are the same.
* @throws FileNotFoundException if the source does not exist.
- * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
+ * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed.
* @since 1.1
*/
public static void copyDirectory(final File srcDir, final File destDir, final boolean preserveFileDate)
@@ -618,14 +618,14 @@ public static void copyDirectory(final File srcDir, final File destDir, final bo
* FileUtils.copyDirectory(srcDir, destDir, filter);
*
*
- * @param srcDir an existing directory to copy, must not be {@code null}.
- * @param destDir the new directory, must not be {@code null}.
- * @param filter the filter to apply, null means copy all directories and files should be the same as the original.
+ * @param srcDir An existing directory to copy, must not be {@code null}.
+ * @param destDir The new directory, must not be {@code null}.
+ * @param filter The filter to apply, null means copy all directories and files should be the same as the original.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IllegalArgumentException if {@code srcDir} exists but is not a directory, or
- * the source and the destination directory are the same
+ * the source and the destination directory are the same.
* @throws FileNotFoundException if the source does not exist.
- * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
+ * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed.
* @since 1.4
*/
public static void copyDirectory(final File srcDir, final File destDir, final FileFilter filter)
@@ -669,13 +669,13 @@ public static void copyDirectory(final File srcDir, final File destDir, final Fi
* FileUtils.copyDirectory(srcDir, destDir, filter, false);
*
*
- * @param srcDir an existing directory to copy, must not be {@code null}.
- * @param destDir the new directory, must not be {@code null}.
- * @param filter the filter to apply, null means copy all directories and files.
+ * @param srcDir An existing directory to copy, must not be {@code null}.
+ * @param destDir The new directory, must not be {@code null}.
+ * @param filter The filter to apply, null means copy all directories and files.
* @param preserveFileDate true if the file date of the copy should be the same as the original.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IllegalArgumentException if {@code srcDir} exists but is not a directory,
- * the source and the destination directory are the same, or the destination is not writable
+ * the source and the destination directory are the same, or the destination is not writable.
* @throws FileNotFoundException if the source does not exist.
* @throws IOException if an error occurs or setting the last-modified time didn't succeed.
* @since 1.4
@@ -720,16 +720,16 @@ public static void copyDirectory(final File srcDir, final File destDir, final Fi
* FileUtils.copyDirectory(srcDir, destDir, filter, false);
*
*
- * @param srcDir an existing directory to copy, must not be {@code null}
- * @param destDir the new directory, must not be {@code null}
- * @param fileFilter the filter to apply, null means copy all directories and files
- * @param preserveFileDate true if the file date of the copy should be the same as the original
+ * @param srcDir An existing directory to copy, must not be {@code null}
+ * @param destDir The new directory, must not be {@code null}
+ * @param fileFilter The filter to apply, null means copy all directories and files.
+ * @param preserveFileDate true if the file date of the copy should be the same as the original.
* @param copyOptions options specifying how the copy should be done, for example {@link StandardCopyOption}.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IllegalArgumentException if {@code srcDir} exists but is not a directory, or
- * the source and the destination directory are the same
+ * the source and the destination directory are the same.
* @throws FileNotFoundException if the source does not exist.
- * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
+ * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed.
* @since 2.8.0
*/
public static void copyDirectory(final File srcDir, final File destDir, final FileFilter fileFilter, final boolean preserveFileDate,
@@ -770,12 +770,12 @@ public static void copyDirectory(final File srcDir, final File destDir, final Fi
* {@link File#setLastModified(long)} and if that fails, the method throws IOException.
*
*
- * @param sourceDir an existing directory to copy, must not be {@code null}.
- * @param destinationDir the directory to place the copy in, must not be {@code null}.
+ * @param sourceDir An existing directory to copy, must not be {@code null}.
+ * @param destinationDir The directory to place the copy in, must not be {@code null}.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IllegalArgumentException if the source or destination is invalid.
* @throws FileNotFoundException if the source does not exist.
- * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
+ * @throws IOException if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed.
* @since 1.2
*/
public static void copyDirectoryToDirectory(final File sourceDir, final File destinationDir) throws IOException {
@@ -798,8 +798,8 @@ public static void copyDirectoryToDirectory(final File sourceDir, final File des
* {@link File#setLastModified(long)}, and if that fails, the method throws IOException.
*
*
- * @param srcFile an existing file to copy, must not be {@code null}.
- * @param destFile the new file, must not be {@code null}.
+ * @param srcFile An existing file to copy, must not be {@code null}.
+ * @param destFile The new file, must not be {@code null}.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IOException if source or destination is invalid.
* @throws IOException if an error occurs or setting the last-modified time didn't succeed.
@@ -825,13 +825,13 @@ public static void copyFile(final File srcFile, final File destFile) throws IOEx
* {@link File#setLastModified(long)}, and if that fails, the method throws IOException.
*
*
- * @param srcFile an existing file to copy, must not be {@code null}.
- * @param destFile the new file, must not be {@code null}.
+ * @param srcFile An existing file to copy, must not be {@code null}.
+ * @param destFile The new file, must not be {@code null}.
* @param preserveFileDate true if the file date of the copy should be the same as the original.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IOException if source or destination is invalid.
* @throws IOException if an error occurs or setting the last-modified time didn't succeed.
- * @throws IOException if the output file length is not the same as the input file length after the copy completes
+ * @throws IOException if the output file length is not the same as the input file length after the copy completes.
* @see #copyFile(File, File, boolean, CopyOption...)
*/
public static void copyFile(final File srcFile, final File destFile, final boolean preserveFileDate) throws IOException {
@@ -858,16 +858,16 @@ public static void copyFile(final File srcFile, final File destFile, final boole
* {@link File#setLastModified(long)}, and if that fails, the method throws IOException.
*
*
- * @param srcFile an existing file to copy, must not be {@code null}.
- * @param destFile the new file, must not be {@code null}.
+ * @param srcFile An existing file to copy, must not be {@code null}.
+ * @param destFile The new file, must not be {@code null}.
* @param preserveFileDate true if the file date of the copy should be the same as the original.
* @param copyOptions options specifying how the copy should be done, for example {@link StandardCopyOption}.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws FileNotFoundException if the source does not exist.
- * @throws IllegalArgumentException if {@code srcFile} or {@code destFile} is not a file
+ * @throws IllegalArgumentException if {@code srcFile} or {@code destFile} is not a file.
* @throws IOException if the output file length is not the same as the input file length after the copy completes.
* @throws IOException if an I/O error occurs, setting the last-modified time didn't succeed,
- * or the destination is not writable
+ * or the destination is not writable.
* @see #copyFileToDirectory(File, File, boolean)
* @since 2.8.0
*/
@@ -895,8 +895,8 @@ public static void copyFile(final File srcFile, final File destFile, final boole
* it if you use {@link StandardCopyOption#REPLACE_EXISTING}.
*
*
- * @param srcFile an existing file to copy, must not be {@code null}.
- * @param destFile the new file, must not be {@code null}.
+ * @param srcFile An existing file to copy, must not be {@code null}.
+ * @param destFile The new file, must not be {@code null}.
* @param copyOptions options specifying how the copy should be done, for example {@link StandardCopyOption}.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws FileNotFoundException if the source does not exist.
@@ -915,9 +915,9 @@ public static void copyFile(final File srcFile, final File destFile, final CopyO
* This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param input the {@link File} to read.
- * @param output the {@link OutputStream} to write.
- * @return the number of bytes copied
+ * @param input The {@link File} to read.
+ * @param output The {@link OutputStream} to write.
+ * @return The number of bytes copied.
* @throws NullPointerException if the File is {@code null}.
* @throws NullPointerException if the OutputStream is {@code null}.
* @throws IOException if an I/O error occurs.
@@ -943,8 +943,8 @@ public static long copyFile(final File input, final OutputStream output) throws
* {@link File#setLastModified(long)} and if that fails, the method throws IOException.
*
*
- * @param srcFile an existing file to copy, must not be {@code null}.
- * @param destDir the directory to place the copy in, must not be {@code null}.
+ * @param srcFile An existing file to copy, must not be {@code null}.
+ * @param destDir The directory to place the copy in, must not be {@code null}.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IllegalArgumentException if source or destination is invalid.
* @throws IOException if an error occurs or setting the last-modified time didn't succeed.
@@ -968,8 +968,8 @@ public static void copyFileToDirectory(final File srcFile, final File destDir) t
* {@link File#setLastModified(long)} and if that fails, the method throws IOException.
*
*
- * @param sourceFile an existing file to copy, must not be {@code null}.
- * @param destinationDir the directory to place the copy in, must not be {@code null}.
+ * @param sourceFile An existing file to copy, must not be {@code null}.
+ * @param destinationDir The directory to place the copy in, must not be {@code null}.
* @param preserveFileDate true if the file date of the copy should be the same as the original.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IOException if an error occurs or setting the last-modified time didn't succeed.
@@ -995,13 +995,13 @@ public static void copyFileToDirectory(final File sourceFile, final File destina
* See {@link #copyToFile(InputStream, File)} for a method that does not close the input stream.
*
*
- * @param source the {@link InputStream} to copy bytes from, must not be {@code null}, will be closed
- * @param destination the non-directory {@link File} to write bytes to
+ * @param source The {@link InputStream} to copy bytes from, must not be {@code null}, will be closed.
+ * @param destination The non-directory {@link File} to write bytes to
* (possibly overwriting), must not be {@code null}
- * @throws IOException if {@code destination} is a directory
- * @throws IOException if {@code destination} cannot be written
- * @throws IOException if {@code destination} needs creating but can't be
- * @throws IOException if an IO error occurs during copying
+ * @throws IOException if {@code destination} is a directory.
+ * @throws IOException if {@code destination} cannot be written.
+ * @throws IOException if {@code destination} needs creating but can't be.
+ * @throws IOException if an IO error occurs during copying.
* @since 2.0
*/
public static void copyInputStreamToFile(final InputStream source, final File destination) throws IOException {
@@ -1027,8 +1027,8 @@ public static void copyInputStreamToFile(final InputStream source, final File de
* {@link File#setLastModified(long)} and if that fails, the method throws IOException.
*
*
- * @param sourceFile an existing file or directory to copy, must not be {@code null}.
- * @param destinationDir the directory to place the copy in, must not be {@code null}.
+ * @param sourceFile An existing file or directory to copy, must not be {@code null}.
+ * @param destinationDir The directory to place the copy in, must not be {@code null}.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IllegalArgumentException if the source or destination is invalid.
* @throws FileNotFoundException if the source does not exist.
@@ -1064,7 +1064,7 @@ public static void copyToDirectory(final File sourceFile, final File destination
*
*
* @param sourceIterable existing files to copy, must not be {@code null}.
- * @param destinationDir the directory to place the copies in, must not be {@code null}.
+ * @param destinationDir The directory to place the copies in, must not be {@code null}.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IOException if source or destination is invalid.
* @throws IOException if an error occurs or setting the last-modified time didn't succeed.
@@ -1085,8 +1085,8 @@ public static void copyToDirectory(final Iterable sourceIterable, final Fi
* {@link java.util.zip.ZipInputStream ZipInputStream}. See {@link #copyInputStreamToFile(InputStream, File)} for a
* method that closes the input stream.
*
- * @param inputStream the {@link InputStream} to copy bytes from, must not be {@code null}
- * @param file the non-directory {@link File} to write bytes to (possibly overwriting), must not be
+ * @param inputStream The {@link InputStream} to copy bytes from, must not be {@code null}
+ * @param file The non-directory {@link File} to write bytes to (possibly overwriting), must not be
* {@code null}
* @throws NullPointerException if the InputStream is {@code null}.
* @throws NullPointerException if the File is {@code null}.
@@ -1113,14 +1113,14 @@ public static void copyToFile(final InputStream inputStream, final File file) th
* with reasonable timeouts to prevent this.
*
*
- * @param source the {@link URL} to copy bytes from, must not be {@code null}
- * @param destination the non-directory {@link File} to write bytes to
+ * @param source The {@link URL} to copy bytes from, must not be {@code null}
+ * @param destination The non-directory {@link File} to write bytes to
* (possibly overwriting), must not be {@code null}
- * @throws IOException if {@code source} URL cannot be opened
- * @throws IOException if {@code destination} is a directory
- * @throws IOException if {@code destination} cannot be written
- * @throws IOException if {@code destination} needs creating but can't be
- * @throws IOException if an IO error occurs during copying
+ * @throws IOException if {@code source} URL cannot be opened.
+ * @throws IOException if {@code destination} is a directory.
+ * @throws IOException if {@code destination} cannot be written.
+ * @throws IOException if {@code destination} needs creating but can't be.
+ * @throws IOException if an IO error occurs during copying.
*/
public static void copyURLToFile(final URL source, final File destination) throws IOException {
final Path path = destination.toPath();
@@ -1133,18 +1133,18 @@ public static void copyURLToFile(final URL source, final File destination) throw
* {@code destination} will be created if they don't already exist. {@code destination} will be
* overwritten if it already exists.
*
- * @param source the {@link URL} to copy bytes from, must not be {@code null}
- * @param destination the non-directory {@link File} to write bytes to (possibly overwriting), must not be
+ * @param source The {@link URL} to copy bytes from, must not be {@code null}
+ * @param destination The non-directory {@link File} to write bytes to (possibly overwriting), must not be
* {@code null}
- * @param connectionTimeoutMillis the number of milliseconds until this method will time out if no connection could
+ * @param connectionTimeoutMillis The number of milliseconds until this method will time out if no connection could
* be established to the {@code source}
- * @param readTimeoutMillis the number of milliseconds until this method will time out if no data could be read from
+ * @param readTimeoutMillis The number of milliseconds until this method will time out if no data could be read from
* the {@code source}
- * @throws IOException if {@code source} URL cannot be opened
- * @throws IOException if {@code destination} is a directory
- * @throws IOException if {@code destination} cannot be written
- * @throws IOException if {@code destination} needs creating but can't be
- * @throws IOException if an IO error occurs during copying
+ * @throws IOException if {@code source} URL cannot be opened.
+ * @throws IOException if {@code destination} is a directory.
+ * @throws IOException if {@code destination} cannot be written.
+ * @throws IOException if {@code destination} needs creating but can't be.
+ * @throws IOException if an IO error occurs during copying.
* @since 2.0
*/
public static void copyURLToFile(final URL source, final File destination, final int connectionTimeoutMillis, final int readTimeoutMillis)
@@ -1162,7 +1162,7 @@ public static void copyURLToFile(final URL source, final File destination, final
* Creates all parent directories for a File object, including any necessary but non-existent parent directories. If a parent directory already exists or
* is null, nothing happens.
*
- * @param file the File that may need parents, may be null.
+ * @param file The File that may need parents, may be null.
* @return The parent directory, or {@code null} if the given File does have a parent.
* @throws IOException if the directory was not created along with all its parent directories.
* @throws SecurityException See {@link File#mkdirs()}.
@@ -1175,7 +1175,7 @@ public static File createParentDirectories(final File file) throws IOException {
/**
* Gets the current directory.
*
- * @return the current directory.
+ * @return The current directory.
* @since 2.12.0
*/
public static File current() {
@@ -1234,8 +1234,8 @@ static String decodeUrl(final String url) {
* boolean.
*
* @param file The file to delete.
- * @return the given file.
- * @throws NullPointerException if the parameter is {@code null}
+ * @return The given file.
+ * @throws NullPointerException if the parameter is {@code null}.
* @throws IOException if the file cannot be deleted.
* @see File#delete()
* @since 2.9.0
@@ -1249,10 +1249,10 @@ public static File delete(final File file) throws IOException {
/**
* Deletes a directory recursively.
*
- * @param directory directory to delete
- * @throws IOException in case deletion is unsuccessful
- * @throws NullPointerException if the parameter is {@code null}
- * @throws IllegalArgumentException if {@code directory} is not a directory
+ * @param directory directory to delete.
+ * @throws IOException in case deletion is unsuccessful.
+ * @throws NullPointerException if the parameter is {@code null}.
+ * @throws IllegalArgumentException if {@code directory} is not a directory.
*/
public static void deleteDirectory(final File directory) throws IOException {
Objects.requireNonNull(directory, "directory");
@@ -1269,8 +1269,8 @@ public static void deleteDirectory(final File directory) throws IOException {
* Requests a directory for deletion recursively when the virtual machine terminates.
*
* @param directory directory to delete, must not be {@code null}
- * @throws NullPointerException if the directory is {@code null}
- * @throws IOException in case deletion is unsuccessful
+ * @throws NullPointerException if the directory is {@code null}.
+ * @throws IOException in case deletion is unsuccessful.
*/
private static void deleteDirectoryOnExit(final File directory) throws IOException {
if (!directory.exists()) {
@@ -1292,9 +1292,9 @@ private static void deleteDirectoryOnExit(final File directory) throws IOExcepti
*
No exceptions are thrown when a file or directory cannot be deleted.
*
*
- * @param file file or directory to delete, can be {@code null}
+ * @param file file or directory to delete, can be {@code null}.
* @return {@code true} if the file or directory was deleted, otherwise
- * {@code false}
+ * {@code false}.
* @since 1.4
*/
public static boolean deleteQuietly(final File file) {
@@ -1329,8 +1329,8 @@ public static boolean deleteQuietly(final File file) {
*
A null child file is not contained in any parent: return false
*
*
- * @param directory the file to consider as the parent.
- * @param child the file to consider as the child.
+ * @param directory The file to consider as the parent.
+ * @param child The file to consider as the child.
* @return true is the candidate leaf is under by the specified composite. False otherwise.
* @throws IOException if an IO error occurs while checking the files.
* @throws NullPointerException if the parent is {@code null}.
@@ -1353,14 +1353,14 @@ public static boolean directoryContains(final File directory, final File child)
* Internal copy directory method. Creates all destination parent directories,
* including any necessary but non-existent parent directories.
*
- * @param srcDir the validated source directory, must not be {@code null}.
- * @param destDir the validated destination directory, must not be {@code null}.
- * @param fileFilter the filter to apply, null means copy all directories and files.
+ * @param srcDir The validated source directory, must not be {@code null}.
+ * @param destDir The validated destination directory, must not be {@code null}.
+ * @param fileFilter The filter to apply, null means copy all directories and files.
* @param exclusionList List of files and directories to exclude from the copy, may be null.
* @param preserveDirDate preserve the directories last modified dates.
* @param copyOptions options specifying how the copy should be done, see {@link StandardCopyOption}.
* @throws IOException if the directory was not created along with all its parent directories.
- * @throws IllegalArgumentException if {@code destDir} is not writable
+ * @throws IllegalArgumentException if {@code destDir} is not writable.
* @throws SecurityException See {@link File#mkdirs()}.
*/
private static void doCopyDirectory(final File srcDir, final File destDir, final FileFilter fileFilter, final List exclusionList,
@@ -1463,7 +1463,7 @@ public static void forceDeleteOnExit(final File file) throws IOException {
* Calls {@link File#mkdirs()} and throws an {@link IOException} on failure.
*
*
- * @param directory the receiver for {@code mkdirs()}. If the {@code directory} already exists or is null, nothing happens.
+ * @param directory The receiver for {@code mkdirs()}. If the {@code directory} already exists or is null, nothing happens.
* @throws IOException if the directory was not created along with all its parent directories.
* @throws IOException if the given file object is not a directory.
* @throws SecurityException See {@link File#mkdirs()}.
@@ -1494,9 +1494,9 @@ public static void forceMkdirParent(final File file) throws IOException {
/**
* Constructs a file from the set of name elements.
*
- * @param directory the parent directory.
- * @param names the name elements.
- * @return the new file.
+ * @param directory The parent directory.
+ * @param names The name elements.
+ * @return The new file.
* @since 2.1
*/
public static File getFile(final File directory, final String... names) {
@@ -1512,8 +1512,8 @@ public static File getFile(final File directory, final String... names) {
/**
* Constructs a file from the set of name elements.
*
- * @param names the name elements.
- * @return the file.
+ * @param names The name elements.
+ * @return The file.
* @since 2.1
*/
public static File getFile(final String... names) {
@@ -1540,9 +1540,9 @@ private static File getParentFile(final File file) {
}
/**
- * Gets a {@link File} representing the system temporary directory.
+ * Gets a {@link File} representing the system temporary directory based on the Java system property {@code java.io.tmpdir}.
*
- * @return the system temporary directory as a File
+ * @return The system temporary directory as a File.
* @since 2.0
*/
public static File getTempDirectory() {
@@ -1550,14 +1550,13 @@ public static File getTempDirectory() {
}
/**
- * Getsv the path to the system temporary directory.
- *
- * WARNING: this method relies on the Java system property 'java.io.tmpdir'
- * which may or may not have a trailing file separator.
- * This can affect code that uses String processing to manipulate pathnames rather
- * than the standard libary methods in classes such as {@link File}
+ * Gets the path to the system temporary directory.
+ *
+ * WARNING: This method reads the Java system property {@code java.io.tmpdir}, which may or may not have a trailing file separator. This can affect code
+ * that uses String processing to manipulate pathnames rather than the standard library methods in classes such as {@link File}.
+ *
*
- * @return the path to the system temporary directory as a String
+ * @return The path to the system temporary directory as a String.
* @since 2.0
*/
public static String getTempDirectoryPath() {
@@ -1565,9 +1564,9 @@ public static String getTempDirectoryPath() {
}
/**
- * Gets a {@link File} representing the user's home directory.
+ * Gets a {@link File} representing the user's home directory based on the Java system property {@code user.home}.
*
- * @return the user's home directory.
+ * @return The user's home directory.
* @since 2.0
*/
public static File getUserDirectory() {
@@ -1575,9 +1574,9 @@ public static File getUserDirectory() {
}
/**
- * Gets the path to the user's home directory.
+ * Gets the path to the user's home directory based on the Java system property {@code user.home}.
*
- * @return the path to the user's home directory.
+ * @return The path to the user's home directory.
* @since 2.0
*/
public static String getUserDirectoryPath() {
@@ -1589,7 +1588,7 @@ public static String getUserDirectoryPath() {
* null-safe delegate to {@link Files#isDirectory(Path path, LinkOption... options)}.
*
* @param file the path to the file.
- * @param options options indicating how symbolic links are handled
+ * @param options options indicating how symbolic links are handled.
* @return {@code true} if the file is a directory; {@code false} if
* the path is null, the file does not exist, is not a directory, or it cannot
* be determined if the file is a directory or not.
@@ -1605,7 +1604,7 @@ public static boolean isDirectory(final File file, final LinkOption... options)
/**
* Tests whether the directory is empty.
*
- * @param directory the directory to query.
+ * @param directory The directory to query.
* @return whether the directory is empty.
* @throws IOException if an I/O error occurs.
* @throws NotDirectoryException if the file could not otherwise be opened because it is not a directory
@@ -1628,11 +1627,11 @@ public static boolean isEmptyDirectory(final File directory) throws IOException
* {@code zoneId} is a valid {@link ZoneId}.
*
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoLocalDate the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDate The date reference.
* @return true if the {@link File} exists and has been modified after the given
* {@link ChronoLocalDate} at the current time.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @throws NullPointerException if the file or local date is {@code null}.
* @since 2.8.0
*/
@@ -1651,12 +1650,12 @@ public static boolean isFileNewer(final File file, final ChronoLocalDate chronoL
* {@link ZoneId}.
*
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoLocalDate the date reference.
- * @param localTime the time reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDate The date reference.
+ * @param localTime The time reference.
* @return true if the {@link File} exists and has been modified after the given
* {@link ChronoLocalDate} at the given time.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @throws NullPointerException if the file, local date or zone ID is {@code null}.
* @since 2.8.0
*/
@@ -1670,13 +1669,13 @@ public static boolean isFileNewer(final File file, final ChronoLocalDate chronoL
* Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDate} at the specified
* {@link OffsetTime}.
*
- * @param file the {@link File} of which the modification date must be compared
- * @param chronoLocalDate the date reference
- * @param offsetTime the time reference
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDate The date reference.
+ * @param offsetTime The time reference.
* @return true if the {@link File} exists and has been modified after the given {@link ChronoLocalDate} at the given
* {@link OffsetTime}.
- * @throws UncheckedIOException if an I/O error occurs
- * @throws NullPointerException if the file, local date or zone ID is {@code null}
+ * @throws UncheckedIOException if an I/O error occurs.
+ * @throws NullPointerException if the file, local date or zone ID is {@code null}.
* @since 2.12.0
*/
public static boolean isFileNewer(final File file, final ChronoLocalDate chronoLocalDate, final OffsetTime offsetTime) {
@@ -1696,11 +1695,11 @@ public static boolean isFileNewer(final File file, final ChronoLocalDate chronoL
* {@link ZoneId}.
*
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoLocalDateTime the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDateTime The date reference.
* @return true if the {@link File} exists and has been modified after the given
* {@link ChronoLocalDateTime} at the system-default time zone.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @throws NullPointerException if the file or local date time is {@code null}.
* @since 2.8.0
*/
@@ -1712,12 +1711,12 @@ public static boolean isFileNewer(final File file, final ChronoLocalDateTime>
* Tests if the specified {@link File} is newer than the specified {@link ChronoLocalDateTime}
* at the specified {@link ZoneId}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoLocalDateTime the date reference.
- * @param zoneId the time zone.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDateTime The date reference.
+ * @param zoneId The time zone.
* @return true if the {@link File} exists and has been modified after the given
* {@link ChronoLocalDateTime} at the given {@link ZoneId}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @throws NullPointerException if the file, local date time or zone ID is {@code null}.
* @since 2.8.0
*/
@@ -1730,12 +1729,12 @@ public static boolean isFileNewer(final File file, final ChronoLocalDateTime>
/**
* Tests if the specified {@link File} is newer than the specified {@link ChronoZonedDateTime}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoZonedDateTime the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoZonedDateTime The date reference.
* @return true if the {@link File} exists and has been modified after the given
* {@link ChronoZonedDateTime}.
* @throws NullPointerException if the file or zoned date time is {@code null}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @since 2.8.0
*/
public static boolean isFileNewer(final File file, final ChronoZonedDateTime> chronoZonedDateTime) {
@@ -1747,11 +1746,11 @@ public static boolean isFileNewer(final File file, final ChronoZonedDateTime>
/**
* Tests if the specified {@link File} is newer than the specified {@link Date}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param date the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param date The date reference.
* @return true if the {@link File} exists and has been modified
* after the given {@link Date}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @throws NullPointerException if the file or date is {@code null}.
*/
public static boolean isFileNewer(final File file, final Date date) {
@@ -1762,8 +1761,8 @@ public static boolean isFileNewer(final File file, final Date date) {
/**
* Tests if the specified {@link File} is newer than the reference {@link File}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param reference the {@link File} of which the modification date is used.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param reference The {@link File} of which the modification date is used.
* @return true if the {@link File} exists and has been modified more
* recently than the reference {@link File}.
* @throws NullPointerException if the file or reference file is {@code null}.
@@ -1776,8 +1775,8 @@ public static boolean isFileNewer(final File file, final File reference) {
/**
* Tests if the specified {@link File} is newer than the specified {@link FileTime}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param fileTime the file time reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param fileTime The file time reference.
* @return true if the {@link File} exists and has been modified after the given {@link FileTime}.
* @throws IOException if an I/O error occurs.
* @throws NullPointerException if the file or local date is {@code null}.
@@ -1791,11 +1790,11 @@ public static boolean isFileNewer(final File file, final FileTime fileTime) thro
/**
* Tests if the specified {@link File} is newer than the specified {@link Instant}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param instant the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param instant The date reference.
* @return true if the {@link File} exists and has been modified after the given {@link Instant}.
* @throws NullPointerException if the file or instant is {@code null}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @since 2.8.0
*/
public static boolean isFileNewer(final File file, final Instant instant) {
@@ -1806,11 +1805,11 @@ public static boolean isFileNewer(final File file, final Instant instant) {
/**
* Tests if the specified {@link File} is newer than the specified time reference.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param timeMillis the time reference measured in milliseconds since the
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param timeMillis The time reference measured in milliseconds since the
* epoch (00:00:00 GMT, January 1, 1970).
* @return true if the {@link File} exists and has been modified after the given time reference.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @throws NullPointerException if the file is {@code null}.
*/
public static boolean isFileNewer(final File file, final long timeMillis) {
@@ -1821,11 +1820,11 @@ public static boolean isFileNewer(final File file, final long timeMillis) {
/**
* Tests if the specified {@link File} is newer than the specified {@link OffsetDateTime}.
*
- * @param file the {@link File} of which the modification date must be compared
- * @param offsetDateTime the date reference
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param offsetDateTime The date reference.
* @return true if the {@link File} exists and has been modified before the given {@link OffsetDateTime}.
- * @throws UncheckedIOException if an I/O error occurs
- * @throws NullPointerException if the file or zoned date time is {@code null}
+ * @throws UncheckedIOException if an I/O error occurs.
+ * @throws NullPointerException if the file or zoned date time is {@code null}.
* @since 2.12.0
*/
public static boolean isFileNewer(final File file, final OffsetDateTime offsetDateTime) {
@@ -1845,12 +1844,12 @@ public static boolean isFileNewer(final File file, final OffsetDateTime offsetDa
* {@code zoneId} is a valid {@link ZoneId}.
*
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoLocalDate the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDate The date reference.
* @return true if the {@link File} exists and has been modified before the given
* {@link ChronoLocalDate} at the current time.
* @throws NullPointerException if the file or local date is {@code null}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @see ZoneId#systemDefault()
* @see LocalTime#now()
* @since 2.8.0
@@ -1870,12 +1869,12 @@ public static boolean isFileOlder(final File file, final ChronoLocalDate chronoL
* {@link ZoneId}.
*
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoLocalDate the date reference.
- * @param localTime the time reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDate The date reference.
+ * @param localTime The time reference.
* @return true if the {@link File} exists and has been modified before the
* given {@link ChronoLocalDate} at the specified time.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @throws NullPointerException if the file, local date or local time is {@code null}.
* @see ZoneId#systemDefault()
* @since 2.8.0
@@ -1890,13 +1889,13 @@ public static boolean isFileOlder(final File file, final ChronoLocalDate chronoL
* Tests if the specified {@link File} is older than the specified {@link ChronoLocalDate} at the specified
* {@link OffsetTime}.
*
- * @param file the {@link File} of which the modification date must be compared
- * @param chronoLocalDate the date reference
- * @param offsetTime the time reference
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDate The date reference.
+ * @param offsetTime The time reference.
* @return true if the {@link File} exists and has been modified after the given {@link ChronoLocalDate} at the given
* {@link OffsetTime}.
- * @throws NullPointerException if the file, local date or zone ID is {@code null}
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws NullPointerException if the file, local date or zone ID is {@code null}.
+ * @throws UncheckedIOException if an I/O error occurs.
* @since 2.12.0
*/
public static boolean isFileOlder(final File file, final ChronoLocalDate chronoLocalDate, final OffsetTime offsetTime) {
@@ -1916,12 +1915,12 @@ public static boolean isFileOlder(final File file, final ChronoLocalDate chronoL
* {@link ZoneId}.
*
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoLocalDateTime the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDateTime The date reference.
* @return true if the {@link File} exists and has been modified before the given
* {@link ChronoLocalDateTime} at the system-default time zone.
* @throws NullPointerException if the file or local date time is {@code null}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @see ZoneId#systemDefault()
* @since 2.8.0
*/
@@ -1933,13 +1932,13 @@ public static boolean isFileOlder(final File file, final ChronoLocalDateTime>
* Tests if the specified {@link File} is older than the specified {@link ChronoLocalDateTime}
* at the specified {@link ZoneId}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoLocalDateTime the date reference.
- * @param zoneId the time zone.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoLocalDateTime The date reference.
+ * @param zoneId The time zone.
* @return true if the {@link File} exists and has been modified before the given
* {@link ChronoLocalDateTime} at the given {@link ZoneId}.
* @throws NullPointerException if the file, local date time or zone ID is {@code null}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @since 2.8.0
*/
public static boolean isFileOlder(final File file, final ChronoLocalDateTime> chronoLocalDateTime, final ZoneId zoneId) {
@@ -1951,12 +1950,12 @@ public static boolean isFileOlder(final File file, final ChronoLocalDateTime>
/**
* Tests if the specified {@link File} is older than the specified {@link ChronoZonedDateTime}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param chronoZonedDateTime the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param chronoZonedDateTime The date reference.
* @return true if the {@link File} exists and has been modified before the given
* {@link ChronoZonedDateTime}.
* @throws NullPointerException if the file or zoned date time is {@code null}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
* @since 2.8.0
*/
public static boolean isFileOlder(final File file, final ChronoZonedDateTime> chronoZonedDateTime) {
@@ -1967,11 +1966,11 @@ public static boolean isFileOlder(final File file, final ChronoZonedDateTime>
/**
* Tests if the specified {@link File} is older than the specified {@link Date}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param date the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param date The date reference.
* @return true if the {@link File} exists and has been modified before the given {@link Date}.
* @throws NullPointerException if the file or date is {@code null}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
*/
public static boolean isFileOlder(final File file, final Date date) {
Objects.requireNonNull(date, "date");
@@ -1981,12 +1980,12 @@ public static boolean isFileOlder(final File file, final Date date) {
/**
* Tests if the specified {@link File} is older than the reference {@link File}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param reference the {@link File} of which the modification date is used.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param reference The {@link File} of which the modification date is used.
* @return true if the {@link File} exists and has been modified before the reference {@link File}.
* @throws NullPointerException if the file or reference file is {@code null}.
* @throws FileNotFoundException if the reference file doesn't exist.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
*/
public static boolean isFileOlder(final File file, final File reference) throws FileNotFoundException {
return Uncheck.getAsBoolean(() -> PathUtils.isOlder(file.toPath(), reference.toPath()));
@@ -1995,8 +1994,8 @@ public static boolean isFileOlder(final File file, final File reference) throws
/**
* Tests if the specified {@link File} is older than the specified {@link FileTime}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param fileTime the file time reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param fileTime The file time reference.
* @return true if the {@link File} exists and has been modified before the given {@link FileTime}.
* @throws IOException if an I/O error occurs.
* @throws NullPointerException if the file or local date is {@code null}.
@@ -2010,8 +2009,8 @@ public static boolean isFileOlder(final File file, final FileTime fileTime) thro
/**
* Tests if the specified {@link File} is older than the specified {@link Instant}.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param instant the date reference.
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param instant The date reference.
* @return true if the {@link File} exists and has been modified before the given {@link Instant}.
* @throws NullPointerException if the file or instant is {@code null}.
* @since 2.8.0
@@ -2024,12 +2023,12 @@ public static boolean isFileOlder(final File file, final Instant instant) {
/**
* Tests if the specified {@link File} is older than the specified time reference.
*
- * @param file the {@link File} of which the modification date must be compared.
- * @param timeMillis the time reference measured in milliseconds since the
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param timeMillis The time reference measured in milliseconds since the
* epoch (00:00:00 GMT, January 1, 1970).
* @return true if the {@link File} exists and has been modified before the given time reference.
* @throws NullPointerException if the file is {@code null}.
- * @throws UncheckedIOException if an I/O error occurs
+ * @throws UncheckedIOException if an I/O error occurs.
*/
public static boolean isFileOlder(final File file, final long timeMillis) {
Objects.requireNonNull(file, PROTOCOL_FILE);
@@ -2039,8 +2038,8 @@ public static boolean isFileOlder(final File file, final long timeMillis) {
/**
* Tests if the specified {@link File} is older than the specified {@link OffsetDateTime}.
*
- * @param file the {@link File} of which the modification date must be compared
- * @param offsetDateTime the date reference
+ * @param file The {@link File} of which the modification date must be compared.
+ * @param offsetDateTime The date reference.
* @return true if the {@link File} exists and has been modified before the given {@link OffsetDateTime}.
* @throws NullPointerException if the file or zoned date time is {@code null}
* @since 2.12.0
@@ -2065,7 +2064,7 @@ private static boolean isFileProtocol(final URL url) {
* null-safe delegate to {@link Files#isRegularFile(Path path, LinkOption... options)}.
*
* @param file the path to the file.
- * @param options options indicating how symbolic links are handled
+ * @param options options indicating how symbolic links are handled.
* @return {@code true} if the file is a regular file; {@code false} if
* the path is null, the file does not exist, is not a regular file, or it cannot
* be determined if the file is a regular file or not.
@@ -2084,7 +2083,7 @@ public static boolean isRegularFile(final File file, final LinkOption... options
* This method delegates to {@link Files#isSymbolicLink(Path path)}
*
*
- * @param file the file to test, may be null.
+ * @param file The file to test, may be null.
* @return true if the file is a symbolic link, see {@link Files#isSymbolicLink(Path path)}.
* @since 2.0
* @see Files#isSymbolicLink(Path)
@@ -2108,7 +2107,7 @@ public static boolean isSymlink(final File file) {
* @param dirFilter optional filter to apply when finding subdirectories.
* If this parameter is {@code null}, subdirectories will not be included in the
* search. Use TrueFileFilter.INSTANCE to match all directories.
- * @return an iterator of {@link File} for the matching files.
+ * @return An iterator of {@link File} for the matching files.
* @see org.apache.commons.io.filefilter.FileFilterUtils
* @see org.apache.commons.io.filefilter.NameFileFilter
* @since 1.2
@@ -2125,10 +2124,10 @@ public static Iterator iterateFiles(final File directory, final IOFileFilt
*
*
* @param directory The directory to search.
- * @param extensions an array of extensions, for example, {"java", "xml"}. If this
+ * @param extensions An array of extensions, for example, {"java", "xml"}. If this
* parameter is {@code null}, all files are returned.
* @param recursive if true all subdirectories are searched as well.
- * @return an iterator of {@link File} with the matching files.
+ * @return An iterator of {@link File} with the matching files.
* @since 1.2
*/
public static Iterator iterateFiles(final File directory, final String[] extensions, final boolean recursive) {
@@ -2153,7 +2152,7 @@ public static Iterator iterateFiles(final File directory, final String[] e
* @param dirFilter optional filter to apply when finding subdirectories.
* If this parameter is {@code null}, subdirectories will not be included in the
* search. Use TrueFileFilter.INSTANCE to match all directories.
- * @return an iterator of {@link File} for the matching files.
+ * @return An iterator of {@link File} for the matching files.
* @see org.apache.commons.io.filefilter.FileFilterUtils
* @see org.apache.commons.io.filefilter.NameFileFilter
* @since 2.2
@@ -2234,8 +2233,8 @@ public static long lastModifiedUnchecked(final File file) {
/**
* Returns an Iterator for the lines in a {@link File} using the default encoding for the VM.
*
- * @param file the file to open for input, must not be {@code null}.
- * @return an Iterator of the lines in the file, never {@code null}.
+ * @param file The file to open for input, must not be {@code null}.
+ * @return An Iterator of the lines in the file, never {@code null}.
* @throws NullPointerException if file is {@code null}.
* @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some
* other reason cannot be opened for reading.
@@ -2274,9 +2273,9 @@ public static LineIterator lineIterator(final File file) throws IOException {
* underlying stream is closed.
*
*
- * @param file the file to open for input, must not be {@code null}.
- * @param charsetName the name of the requested charset, {@code null} means platform default.
- * @return a LineIterator for lines in the file, never {@code null}; MUST be closed by the caller.
+ * @param file The file to open for input, must not be {@code null}.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @return A LineIterator for lines in the file, never {@code null}; MUST be closed by the caller.
* @throws NullPointerException if file is {@code null}.
* @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some
* other reason cannot be opened for reading.
@@ -2290,7 +2289,7 @@ public static LineIterator lineIterator(final File file, final String charsetNam
inputStream = Files.newInputStream(file.toPath());
return IOUtils.lineIterator(inputStream, charsetName);
} catch (final IOException | RuntimeException ex) {
- IOUtils.closeQuietly(inputStream, ex::addSuppressed);
+ IOUtils.closeQuietlySuppress(inputStream, ex);
throw ex;
}
}
@@ -2363,7 +2362,7 @@ private static File[] listFiles(final File directory, final FileFilter fileFilte
* @param dirFilter optional filter to apply when finding subdirectories.
* If this parameter is {@code null}, subdirectories will not be included in the
* search. Use {@link TrueFileFilter#INSTANCE} to match all directories.
- * @return a collection of {@link File} with the matching files.
+ * @return A collection of {@link File} with the matching files.
* @see org.apache.commons.io.filefilter.FileFilterUtils
* @see org.apache.commons.io.filefilter.NameFileFilter
*/
@@ -2407,10 +2406,10 @@ private static List listFiles(final File directory, final List files
* which match an array of extensions.
*
* @param directory The directory to search.
- * @param extensions an array of extensions, for example, {"java", "xml"}. If this
+ * @param extensions An array of extensions, for example, {"java", "xml"}. If this
* parameter is {@code null}, all files are returned.
* @param recursive if true all subdirectories are searched as well.
- * @return a collection of {@link File} with the matching files.
+ * @return A collection of {@link File} with the matching files.
*/
public static Collection listFiles(final File directory, final String[] extensions, final boolean recursive) {
return listFiles(directory, new ArrayList<>(), recursive, extensions != null ? toSuffixFileFilter(extensions) : TrueFileFilter.INSTANCE);
@@ -2429,7 +2428,7 @@ public static Collection listFiles(final File directory, final String[] ex
* @param dirFilter optional filter to apply when finding subdirectories.
* If this parameter is {@code null}, subdirectories will not be included in the
* search. Use TrueFileFilter.INSTANCE to match all directories.
- * @return a collection of {@link File} with the matching files.
+ * @return A collection of {@link File} with the matching files.
* @see org.apache.commons.io.FileUtils#listFiles
* @see org.apache.commons.io.filefilter.FileFilterUtils
* @see org.apache.commons.io.filefilter.NameFileFilter
@@ -2450,8 +2449,8 @@ public static Collection listFilesAndDirs(final File directory, final IOFi
* null, nothing happens.
*
*
- * @param directory the receiver for {@code mkdirs()}. If the {@code directory} already exists or is null, nothing happens.
- * @return the given directory.
+ * @param directory The receiver for {@code mkdirs()}. If the {@code directory} already exists or is null, nothing happens.
+ * @return The given directory.
* @throws IOException if the directory was not created along with all its parent directories.
* @throws IOException if the given file object is not a directory.
* @throws SecurityException See {@link File#mkdirs()}.
@@ -2470,8 +2469,8 @@ private static File mkdirs(final File directory) throws IOException {
* When the destination directory is on another file system, do a "copy and delete".
*
*
- * @param srcDir the directory to be moved.
- * @param destDir the destination directory.
+ * @param srcDir The directory to be moved.
+ * @param destDir The destination directory.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws IllegalArgumentException if {@code srcDir} exists but is not a directory.
* @throws FileNotFoundException if the source does not exist.
@@ -2501,8 +2500,8 @@ public static void moveDirectory(final File srcDir, final File destDir) throws I
* If {@code createDestDir} is true, creates all destination parent directories, including any necessary but non-existent parent directories.
*
*
- * @param source the directory to be moved.
- * @param destDir the destination file.
+ * @param source The directory to be moved.
+ * @param destDir The destination file.
* @param createDestDir If {@code true} create the destination directory, otherwise if {@code false} throw an
* IOException.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
@@ -2536,8 +2535,8 @@ public static void moveDirectoryToDirectory(final File source, final File destDi
* When the destination file is on another file system, do a "copy and delete".
*
*
- * @param srcFile the file to be moved.
- * @param destFile the destination file.
+ * @param srcFile The file to be moved.
+ * @param destFile The destination file.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws FileExistsException if the destination file exists.
* @throws FileNotFoundException if the source file does not exist.
@@ -2555,8 +2554,8 @@ public static void moveFile(final File srcFile, final File destFile) throws IOEx
* When the destination file is on another file system, do a "copy and delete".
*
*
- * @param srcFile the file to be moved.
- * @param destFile the destination file.
+ * @param srcFile The file to be moved.
+ * @param destFile The destination file.
* @param copyOptions Copy options.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws FileExistsException if the destination file exists.
@@ -2586,8 +2585,8 @@ public static void moveFile(final File srcFile, final File destFile, final CopyO
* If {@code createDestDir} is true, creates all destination parent directories, including any necessary but non-existent parent directories.
*
*
- * @param srcFile the file to be moved.
- * @param destDir the directory to move the file into.
+ * @param srcFile The file to be moved.
+ * @param destDir The directory to move the file into.
* @param createDestDir if {@code true} create the destination directory. If {@code false} throw an
* IOException if the destination directory does not already exist.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
@@ -2618,8 +2617,8 @@ public static void moveFileToDirectory(final File srcFile, final File destDir, f
* When the destination is on another file system, do a "copy and delete".
*
*
- * @param src the file or directory to be moved.
- * @param destDir the destination directory.
+ * @param src The file or directory to be moved.
+ * @param destDir The destination directory.
* @param createDestDir if {@code true} create the destination directory. If {@code false} throw an
* IOException if the destination directory does not already exist.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
@@ -2643,8 +2642,8 @@ public static void moveToDirectory(final File src, final File destDir, final boo
* to the file.
*
* @param append Whether or not to append.
- * @param file the File.
- * @return a new OutputStream.
+ * @param file The File.
+ * @return A new OutputStream.
* @throws IOException if an I/O error occurs.
* @see PathUtils#newOutputStream(Path, boolean)
* @since 2.12.0
@@ -2664,8 +2663,8 @@ public static OutputStream newOutputStream(final File file, final boolean append
* directory. An exception is thrown if the file exists but cannot be read.
*
*
- * @param file the file to open for input, must not be {@code null}.
- * @return a new {@link FileInputStream} for the specified file.
+ * @param file The file to open for input, must not be {@code null}.
+ * @return A new {@link FileInputStream} for the specified file.
* @throws NullPointerException if file is {@code null}.
* @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some
* other reason cannot be opened for reading.
@@ -2692,10 +2691,10 @@ public static FileInputStream openInputStream(final File file) throws IOExceptio
* An exception is thrown if the parent directory cannot be created.
*
*
- * @param file the file to open for output, must not be {@code null}.
- * @return a new {@link FileOutputStream} for the specified file
+ * @param file The file to open for output, must not be {@code null}.
+ * @return A new {@link FileOutputStream} for the specified file.
* @throws NullPointerException if the file object is {@code null}.
- * @throws IllegalArgumentException if the file object is a directory
+ * @throws IllegalArgumentException if the file object is a directory.
* @throws IllegalArgumentException if the file is not writable.
* @throws IOException if the directories could not be created.
* @since 1.3
@@ -2719,10 +2718,10 @@ public static FileOutputStream openOutputStream(final File file) throws IOExcept
* An exception is thrown if the parent directory cannot be created.
*
*
- * @param file the file to open for output, must not be {@code null}.
+ * @param file The file to open for output, must not be {@code null}.
* @param append if {@code true}, then bytes will be added to the
* end of the file rather than overwriting.
- * @return a new {@link FileOutputStream} for the specified file.
+ * @return A new {@link FileOutputStream} for the specified file.
* @throws NullPointerException if the file object is {@code null}.
* @throws IllegalArgumentException if the file object is a directory.
* @throws IOException if the directories could not be created, or the file is not writable.
@@ -2742,8 +2741,8 @@ public static FileOutputStream openOutputStream(final File file, final boolean a
* Reads the contents of a file into a byte array.
* The file is always closed.
*
- * @param file the file to read, must not be {@code null}.
- * @return the file contents, never {@code null}.
+ * @param file The file to read, must not be {@code null}.
+ * @return The file contents, never {@code null}.
* @throws NullPointerException if file is {@code null}.
* @throws IOException if an I/O error occurs, including when the file does not exist, is a directory rather than a
* regular file, or for some other reason why the file cannot be opened for reading.
@@ -2755,11 +2754,11 @@ public static byte[] readFileToByteArray(final File file) throws IOException {
}
/**
- * Reads the contents of a file into a String using the virtual machine's {@link Charset#defaultCharset() default charset}. The
+ * Reads the contents of a file into a String using the virtual machine's {@linkplain Charset#defaultCharset() default charset}. The
* file is always closed.
*
- * @param file the file to read, must not be {@code null}.
- * @return the file contents, never {@code null}.
+ * @param file The file to read, must not be {@code null}.
+ * @return The file contents, never {@code null}.
* @throws NullPointerException if file is {@code null}.
* @throws IOException if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other
* reason why the file cannot be opened for reading.
@@ -2775,9 +2774,9 @@ public static String readFileToString(final File file) throws IOException {
* Reads the contents of a file into a String.
* The file is always closed.
*
- * @param file the file to read, must not be {@code null}.
- * @param charsetName the name of the requested charset, {@code null} means platform default.
- * @return the file contents, never {@code null}.
+ * @param file The file to read, must not be {@code null}.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @return The file contents, never {@code null}.
* @throws NullPointerException if file is {@code null}.
* @throws IOException if an I/O error occurs, including when the file does not exist, is a directory rather than a
* regular file, or for some other reason why the file cannot be opened for reading.
@@ -2790,9 +2789,9 @@ public static String readFileToString(final File file, final Charset charsetName
/**
* Reads the contents of a file into a String. The file is always closed.
*
- * @param file the file to read, must not be {@code null}.
- * @param charsetName the name of the requested charset, {@code null} means platform default.
- * @return the file contents, never {@code null}.
+ * @param file The file to read, must not be {@code null}.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @return The file contents, never {@code null}.
* @throws NullPointerException if file is {@code null}.
* @throws IOException if an I/O error occurs, including when the file does not exist, is a directory rather than a
* regular file, or for some other reason why the file cannot be opened for reading.
@@ -2804,11 +2803,11 @@ public static String readFileToString(final File file, final String charsetName)
}
/**
- * Reads the contents of a file line by line to a List of Strings using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Reads the contents of a file line by line to a List of Strings using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
* The file is always closed.
*
- * @param file the file to read, must not be {@code null}.
- * @return the list of Strings representing each line in the file, never {@code null}.
+ * @param file The file to read, must not be {@code null}.
+ * @return The list of Strings representing each line in the file, never {@code null}.
* @throws NullPointerException if file is {@code null}.
* @throws IOException if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other
* reason why the file cannot be opened for reading.
@@ -2824,9 +2823,9 @@ public static List readLines(final File file) throws IOException {
* Reads the contents of a file line by line to a List of Strings.
* The file is always closed.
*
- * @param file the file to read, must not be {@code null}.
- * @param charset the charset to use, {@code null} means platform default.
- * @return the list of Strings representing each line in the file, never {@code null}.
+ * @param file The file to read, must not be {@code null}.
+ * @param charset The charset to use, {@code null} means platform default.
+ * @return The list of Strings representing each line in the file, never {@code null}.
* @throws NullPointerException if file is {@code null}.
* @throws IOException if an I/O error occurs, including when the file does not exist, is a directory rather than a
* regular file, or for some other reason why the file cannot be opened for reading.
@@ -2839,9 +2838,9 @@ public static List readLines(final File file, final Charset charset) thr
/**
* Reads the contents of a file line by line to a List of Strings. The file is always closed.
*
- * @param file the file to read, must not be {@code null}.
- * @param charsetName the name of the requested charset, {@code null} means platform default.
- * @return the list of Strings representing each line in the file, never {@code null}.
+ * @param file The file to read, must not be {@code null}.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @return The list of Strings representing each line in the file, never {@code null}.
* @throws NullPointerException if file is {@code null}.
* @throws IOException if an I/O error occurs, including when the file does not exist, is a directory rather than a
* regular file, or for some other reason why the file cannot be opened for reading.
@@ -2947,10 +2946,10 @@ private static boolean setTimes(final File sourceFile, final File targetFile) {
* method that does not overflow.
*
*
- * @param file the regular file or directory to return the size
+ * @param file The regular file or directory to return the size
* of (must not be {@code null}).
*
- * @return the length of the file, or recursive size of the directory,
+ * @return The length of the file, or recursive size of the directory,
* provided (in bytes).
*
* @throws NullPointerException if the file is {@code null}.
@@ -2969,10 +2968,10 @@ public static long sizeOf(final File file) {
* calculated recursively. If a directory or subdirectory is security
* restricted, its size will not be included.
*
- * @param file the regular file or directory to return the size
+ * @param file The regular file or directory to return the size
* of (must not be {@code null}).
*
- * @return the length of the file, or recursive size of the directory,
+ * @return The length of the file, or recursive size of the directory,
* provided (in bytes).
*
* @throws NullPointerException if the file is {@code null}.
@@ -3037,8 +3036,8 @@ public static BigInteger sizeOfDirectoryAsBigInteger(final File directory) {
*
* @param directory The directory to search.
* @param recursive if true all subdirectories are searched as well.
- * @param extensions an array of extensions, for example, {"java", "xml"}. If this parameter is {@code null}, all files are returned.
- * @return a Stream of {@link File} for matching files.
+ * @param extensions An array of extensions, for example, {"java", "xml"}. If this parameter is {@code null}, all files are returned.
+ * @return A Stream of {@link File} for matching files.
* @throws IOException if an I/O error is thrown when accessing the starting file.
* @since 2.9.0
*/
@@ -3058,8 +3057,8 @@ public static Stream streamFiles(final File directory, final boolean recur
* to characters. Additionally, malformed percent-encoded octets are handled leniently by passing them through literally.
*
*
- * @param url the file URL to convert, {@code null} returns {@code null}.
- * @return the equivalent {@link File} object, or {@code null} if the URL's protocol is not {@code file}.
+ * @param url The file URL to convert, {@code null} returns {@code null}.
+ * @return The equivalent {@link File} object, or {@code null} if the URL's protocol is not {@code file}.
*/
public static File toFile(final URL url) {
if (url == null || !isFileProtocol(url)) {
@@ -3079,8 +3078,8 @@ public static File toFile(final URL url) {
* This method will decode the URL. Syntax such as {@code file:///my%20docs/file.txt} will be correctly decoded to {@code /my docs/file.txt}.
*
*
- * @param urls the file URLs to convert, {@code null} returns empty array.
- * @return a non-{@code null} array of Files matching the input, with a {@code null} item if there was a {@code null} at that index in the input array.
+ * @param urls The file URLs to convert, {@code null} returns empty array.
+ * @return A non-{@code null} array of Files matching the input, with a {@code null} item if there was a {@code null} at that index in the input array.
* @throws IllegalArgumentException if any file is not a URL file.
* @throws IllegalArgumentException if any file is incorrectly encoded.
* @since 1.1
@@ -3109,7 +3108,7 @@ public static File[] toFiles(final URL... urls) {
*
*
* @param stream The stream to consume.
- * @return a new List.
+ * @return A new List.
*/
private static List toList(final Stream stream) {
return stream.collect(Collectors.toList());
@@ -3119,7 +3118,7 @@ private static List toList(final Stream stream) {
* Converts whether or not to recurse into a recursion max depth.
*
* @param recursive whether or not to recurse.
- * @return the recursion depth.
+ * @return The recursion depth.
*/
private static int toMaxDepth(final boolean recursive) {
return recursive ? Integer.MAX_VALUE : 1;
@@ -3128,8 +3127,8 @@ private static int toMaxDepth(final boolean recursive) {
/**
* Converts an array of file extensions to suffixes.
*
- * @param extensions an array of extensions, for example: {@code ["java", "xml"]}.
- * @return an array of suffixes, for example: {@code [".java", ".xml"]}.
+ * @param extensions An array of extensions, for example: {@code ["java", "xml"]}.
+ * @return An array of suffixes, for example: {@code [".java", ".xml"]}.
* @throws NullPointerException if the parameter is null.
*/
private static String[] toSuffixes(final String... extensions) {
@@ -3145,7 +3144,7 @@ private static SuffixFileFilter toSuffixFileFilter(final String... extensions) {
* updates the file's modified time. This method throws an IOException if the last modified date
* of the file cannot be set. It creates parent directories if they do not exist.
*
- * @param file the File to touch.
+ * @param file The File to touch.
* @throws NullPointerException if the parameter is {@code null}.
* @throws IOException if setting the last-modified time failed or an I/O problem occurs.
*/
@@ -3159,8 +3158,8 @@ public static void touch(final File file) throws IOException {
* Returns an array of the same size as the input.
*
*
- * @param files the files to convert, must not be {@code null}.
- * @return an array of URLs matching the input.
+ * @param files The files to convert, must not be {@code null}.
+ * @return An array of URLs matching the input.
* @throws IOException if a file cannot be converted.
* @throws NullPointerException if any argument is null.
*/
@@ -3181,8 +3180,8 @@ public static URL[] toURLs(final File... files) throws IOException {
*
Throws {@link FileNotFoundException} if {@code source} does not exist
*
*
- * @param source the file or directory to be moved.
- * @param destination the destination file or directory.
+ * @param source The file or directory to be moved.
+ * @param destination The destination file or directory.
* @throws NullPointerException if any of the given {@link File}s are {@code null}.
* @throws FileNotFoundException if the source file does not exist.
*/
@@ -3201,8 +3200,8 @@ private static void validateMoveParameters(final File source, final File destina
* true up to the maximum time specified in seconds.
*
*
- * @param file the file to check, must not be {@code null}.
- * @param seconds the maximum time in seconds to wait.
+ * @param file The file to check, must not be {@code null}.
+ * @param seconds The maximum time in seconds to wait.
* @return true if file exists.
* @throws NullPointerException if the file is {@code null}.
*/
@@ -3212,10 +3211,10 @@ public static boolean waitFor(final File file, final int seconds) {
}
/**
- * Writes a CharSequence to a file creating the file if it does not exist using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Writes a CharSequence to a file creating the file if it does not exist using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * @param file the file to write.
- * @param data the content to write to the file.
+ * @param file The file to write.
+ * @param data The content to write to the file.
* @throws IOException in case of an I/O error.
* @since 2.0
* @deprecated Use {@link #write(File, CharSequence, Charset)} instead (and specify the appropriate encoding).
@@ -3226,10 +3225,10 @@ public static void write(final File file, final CharSequence data) throws IOExce
}
/**
- * Writes a CharSequence to a file creating the file if it does not exist using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Writes a CharSequence to a file creating the file if it does not exist using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * @param file the file to write.
- * @param data the content to write to the file.
+ * @param file The file to write.
+ * @param data The content to write to the file.
* @param append if {@code true}, then the data will be added to the end of the file rather than overwriting.
* @throws IOException in case of an I/O error.
* @since 2.1
@@ -3243,9 +3242,9 @@ public static void write(final File file, final CharSequence data, final boolean
/**
* Writes a CharSequence to a file creating the file if it does not exist.
*
- * @param file the file to write.
- * @param data the content to write to the file.
- * @param charset the name of the requested charset, {@code null} means platform default.
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @param charset The name of the requested charset, {@code null} means platform default.
* @throws IOException in case of an I/O error.
* @since 2.3
*/
@@ -3256,9 +3255,9 @@ public static void write(final File file, final CharSequence data, final Charset
/**
* Writes a CharSequence to a file creating the file if it does not exist.
*
- * @param file the file to write.
- * @param data the content to write to the file.
- * @param charset the charset to use, {@code null} means platform default.
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @param charset The charset to use, {@code null} means platform default.
* @param append if {@code true}, then the data will be added to the.
* end of the file rather than overwriting.
* @throws IOException in case of an I/O error.
@@ -3271,11 +3270,11 @@ public static void write(final File file, final CharSequence data, final Charset
/**
* Writes a CharSequence to a file creating the file if it does not exist.
*
- * @param file the file to write
- * @param data the content to write to the file
- * @param charsetName the name of the requested charset, {@code null} means platform default
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @throws IOException in case of an I/O error.
+ * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM.
* @since 2.0
*/
public static void write(final File file, final CharSequence data, final String charsetName) throws IOException {
@@ -3285,13 +3284,13 @@ public static void write(final File file, final CharSequence data, final String
/**
* Writes a CharSequence to a file creating the file if it does not exist.
*
- * @param file the file to write
- * @param data the content to write to the file
- * @param charsetName the name of the requested charset, {@code null} means platform default
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
* @param append if {@code true}, then the data will be added to the
- * end of the file rather than overwriting
- * @throws IOException in case of an I/O error
- * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported by the VM
+ * end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
+ * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported by the VM.
* @since 2.1
*/
public static void write(final File file, final CharSequence data, final String charsetName, final boolean append) throws IOException {
@@ -3304,9 +3303,9 @@ public static void write(final File file, final CharSequence data, final String
* Writes a byte array to a file creating the file if it does not exist.
* The parent directories of the file will be created if they do not exist.
*
- * @param file the file to write to
- * @param data the content to write to the file
- * @throws IOException in case of an I/O error
+ * @param file The file to write to.
+ * @param data The content to write to the file.
+ * @throws IOException in case of an I/O error.
* @since 1.1
*/
public static void writeByteArrayToFile(final File file, final byte[] data) throws IOException {
@@ -3316,11 +3315,11 @@ public static void writeByteArrayToFile(final File file, final byte[] data) thro
/**
* Writes a byte array to a file creating the file if it does not exist.
*
- * @param file the file to write to
- * @param data the content to write to the file
+ * @param file The file to write to.
+ * @param data The content to write to the file.
* @param append if {@code true}, then bytes will be added to the
- * end of the file rather than overwriting
- * @throws IOException in case of an I/O error
+ * end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
* @since 2.1
*/
public static void writeByteArrayToFile(final File file, final byte[] data, final boolean append) throws IOException {
@@ -3332,11 +3331,11 @@ public static void writeByteArrayToFile(final File file, final byte[] data, fina
* at offset {@code off} to a file, creating the file if it does
* not exist.
*
- * @param file the file to write to
- * @param data the content to write to the file
- * @param off the start offset in the data
- * @param len the number of bytes to write
- * @throws IOException in case of an I/O error
+ * @param file The file to write to.
+ * @param data The content to write to the file.
+ * @param off The start offset in the data.
+ * @param len The number of bytes to write.
+ * @throws IOException in case of an I/O error.
* @since 2.5
*/
public static void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len) throws IOException {
@@ -3348,13 +3347,13 @@ public static void writeByteArrayToFile(final File file, final byte[] data, fina
* at offset {@code off} to a file, creating the file if it does
* not exist.
*
- * @param file the file to write to
- * @param data the content to write to the file
- * @param off the start offset in the data
- * @param len the number of bytes to write
+ * @param file The file to write to.
+ * @param data The content to write to the file.
+ * @param off The start offset in the data.
+ * @param len The number of bytes to write.
* @param append if {@code true}, then bytes will be added to the
- * end of the file rather than overwriting
- * @throws IOException in case of an I/O error
+ * end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
* @since 2.5
*/
public static void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len, final boolean append) throws IOException {
@@ -3368,9 +3367,9 @@ public static void writeByteArrayToFile(final File file, final byte[] data, fina
* the specified {@link File} line by line.
* The default VM encoding and the default line ending will be used.
*
- * @param file the file to write to
- * @param lines the lines to write, {@code null} entries produce blank lines
- * @throws IOException in case of an I/O error
+ * @param file The file to write to.
+ * @param lines The lines to write, {@code null} entries produce blank lines.
+ * @throws IOException in case of an I/O error.
* @since 1.3
*/
public static void writeLines(final File file, final Collection> lines) throws IOException {
@@ -3382,11 +3381,11 @@ public static void writeLines(final File file, final Collection> lines) throws
* the specified {@link File} line by line.
* The default VM encoding and the default line ending will be used.
*
- * @param file the file to write to
- * @param lines the lines to write, {@code null} entries produce blank lines
+ * @param file The file to write to.
+ * @param lines The lines to write, {@code null} entries produce blank lines.
* @param append if {@code true}, then the lines will be added to the
- * end of the file rather than overwriting
- * @throws IOException in case of an I/O error
+ * end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
* @since 2.1
*/
public static void writeLines(final File file, final Collection> lines, final boolean append) throws IOException {
@@ -3398,10 +3397,10 @@ public static void writeLines(final File file, final Collection> lines, final
* the specified {@link File} line by line.
* The default VM encoding and the specified line ending will be used.
*
- * @param file the file to write to
- * @param lines the lines to write, {@code null} entries produce blank lines
- * @param lineEnding the line separator to use, {@code null} is system default
- * @throws IOException in case of an I/O error
+ * @param file The file to write to.
+ * @param lines The lines to write, {@code null} entries produce blank lines.
+ * @param lineEnding The line separator to use, {@code null} is system default.
+ * @throws IOException in case of an I/O error.
* @since 1.3
*/
public static void writeLines(final File file, final Collection> lines, final String lineEnding) throws IOException {
@@ -3413,12 +3412,12 @@ public static void writeLines(final File file, final Collection> lines, final
* the specified {@link File} line by line.
* The default VM encoding and the specified line ending will be used.
*
- * @param file the file to write to
- * @param lines the lines to write, {@code null} entries produce blank lines
- * @param lineEnding the line separator to use, {@code null} is system default
+ * @param file The file to write to.
+ * @param lines The lines to write, {@code null} entries produce blank lines.
+ * @param lineEnding The line separator to use, {@code null} is system default.
* @param append if {@code true}, then the lines will be added to the
- * end of the file rather than overwriting
- * @throws IOException in case of an I/O error
+ * end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
* @since 2.1
*/
public static void writeLines(final File file, final Collection> lines, final String lineEnding, final boolean append) throws IOException {
@@ -3431,11 +3430,11 @@ public static void writeLines(final File file, final Collection> lines, final
* The specified character encoding and the default line ending will be used.
* The parent directories of the file will be created if they do not exist.
*
- * @param file the file to write to
- * @param charsetName the name of the requested charset, {@code null} means platform default
- * @param lines the lines to write, {@code null} entries produce blank lines
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
+ * @param file The file to write to.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @param lines The lines to write, {@code null} entries produce blank lines.
+ * @throws IOException in case of an I/O error.
+ * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM.
* @since 1.1
*/
public static void writeLines(final File file, final String charsetName, final Collection> lines) throws IOException {
@@ -3447,13 +3446,13 @@ public static void writeLines(final File file, final String charsetName, final C
* the specified {@link File} line by line, optionally appending.
* The specified character encoding and the default line ending will be used.
*
- * @param file the file to write to
- * @param charsetName the name of the requested charset, {@code null} means platform default
- * @param lines the lines to write, {@code null} entries produce blank lines
+ * @param file The file to write to.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @param lines The lines to write, {@code null} entries produce blank lines.
* @param append if {@code true}, then the lines will be added to the
- * end of the file rather than overwriting
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
+ * end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
+ * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM.
* @since 2.1
*/
public static void writeLines(final File file, final String charsetName, final Collection> lines, final boolean append) throws IOException {
@@ -3466,12 +3465,12 @@ public static void writeLines(final File file, final String charsetName, final C
* The specified character encoding and the line ending will be used.
* The parent directories of the file will be created if they do not exist.
*
- * @param file the file to write to
- * @param charsetName the name of the requested charset, {@code null} means platform default
- * @param lines the lines to write, {@code null} entries produce blank lines
- * @param lineEnding the line separator to use, {@code null} is system default
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
+ * @param file The file to write to.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @param lines The lines to write, {@code null} entries produce blank lines.
+ * @param lineEnding The line separator to use, {@code null} is system default.
+ * @throws IOException in case of an I/O error.
+ * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM.
* @since 1.1
*/
public static void writeLines(final File file, final String charsetName, final Collection> lines, final String lineEnding) throws IOException {
@@ -3483,14 +3482,14 @@ public static void writeLines(final File file, final String charsetName, final C
* the specified {@link File} line by line.
* The specified character encoding and the line ending will be used.
*
- * @param file the file to write to
- * @param charsetName the name of the requested charset, {@code null} means platform default
- * @param lines the lines to write, {@code null} entries produce blank lines
- * @param lineEnding the line separator to use, {@code null} is system default
+ * @param file The file to write to.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @param lines The lines to write, {@code null} entries produce blank lines.
+ * @param lineEnding The line separator to use, {@code null} is system default.
* @param append if {@code true}, then the lines will be added to the
- * end of the file rather than overwriting
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
+ * end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
+ * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM.
* @since 2.1
*/
public static void writeLines(final File file, final String charsetName, final Collection> lines, final String lineEnding, final boolean append)
@@ -3501,12 +3500,12 @@ public static void writeLines(final File file, final String charsetName, final C
}
/**
- * Writes a String to a file creating the file if it does not exist using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Writes a String to a file creating the file if it does not exist using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * @param file the file to write
- * @param data the content to write to the file
- * @throws IOException in case of an I/O error
- * @deprecated Use {@link #writeStringToFile(File, String, Charset)} instead (and specify the appropriate encoding)
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @throws IOException in case of an I/O error.
+ * @deprecated Use {@link #writeStringToFile(File, String, Charset)} instead (and specify the appropriate encoding).
*/
@Deprecated
public static void writeStringToFile(final File file, final String data) throws IOException {
@@ -3514,14 +3513,14 @@ public static void writeStringToFile(final File file, final String data) throws
}
/**
- * Writes a String to a file creating the file if it does not exist using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Writes a String to a file creating the file if it does not exist using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * @param file the file to write
- * @param data the content to write to the file
- * @param append if {@code true}, then the String will be added to the end of the file rather than overwriting
- * @throws IOException in case of an I/O error
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @param append if {@code true}, then the String will be added to the end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
* @since 2.1
- * @deprecated Use {@link #writeStringToFile(File, String, Charset, boolean)} instead (and specify the appropriate encoding)
+ * @deprecated Use {@link #writeStringToFile(File, String, Charset, boolean)} instead (and specify the appropriate encoding).
*/
@Deprecated
public static void writeStringToFile(final File file, final String data, final boolean append) throws IOException {
@@ -3532,11 +3531,11 @@ public static void writeStringToFile(final File file, final String data, final b
* Writes a String to a file creating the file if it does not exist.
* The parent directories of the file will be created if they do not exist.
*
- * @param file the file to write
- * @param data the content to write to the file
- * @param charset the charset to use, {@code null} means platform default
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @param charset The charset to use, {@code null} means platform default.
+ * @throws IOException in case of an I/O error.
+ * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM.
* @since 2.4
*/
public static void writeStringToFile(final File file, final String data, final Charset charset) throws IOException {
@@ -3547,12 +3546,12 @@ public static void writeStringToFile(final File file, final String data, final C
* Writes a String to a file, creating the file if it does not exist.
* The parent directories of the file are created if they do not exist.
*
- * @param file the file to write
- * @param data the content to write to the file
- * @param charset the charset to use, {@code null} means platform default
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @param charset The charset to use, {@code null} means platform default.
* @param append if {@code true}, then the String will be added to the
- * end of the file rather than overwriting
- * @throws IOException in case of an I/O error
+ * end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
* @since 2.3
*/
public static void writeStringToFile(final File file, final String data, final Charset charset, final boolean append) throws IOException {
@@ -3565,11 +3564,11 @@ public static void writeStringToFile(final File file, final String data, final C
* Writes a String to a file, creating the file if it does not exist.
* The parent directories of the file are created if they do not exist.
*
- * @param file the file to write
- * @param data the content to write to the file
- * @param charsetName the name of the requested charset, {@code null} means platform default
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
+ * @throws IOException in case of an I/O error.
+ * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM.
*/
public static void writeStringToFile(final File file, final String data, final String charsetName) throws IOException {
writeStringToFile(file, data, charsetName, false);
@@ -3579,13 +3578,13 @@ public static void writeStringToFile(final File file, final String data, final S
* Writes a String to a file, creating the file if it does not exist.
* The parent directories of the file are created if they do not exist.
*
- * @param file the file to write
- * @param data the content to write to the file
- * @param charsetName the name of the requested charset, {@code null} means platform default
+ * @param file The file to write.
+ * @param data The content to write to the file.
+ * @param charsetName The name of the requested charset, {@code null} means platform default.
* @param append if {@code true}, then the String will be added to the
- * end of the file rather than overwriting
- * @throws IOException in case of an I/O error
- * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported by the VM
+ * end of the file rather than overwriting.
+ * @throws IOException in case of an I/O error.
+ * @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported by the VM.
* @since 2.1
*/
public static void writeStringToFile(final File file, final String data, final String charsetName, final boolean append) throws IOException {
diff --git a/src/main/java/org/apache/commons/io/FilenameUtils.java b/src/main/java/org/apache/commons/io/FilenameUtils.java
index ec836e29421..99964f047ab 100644
--- a/src/main/java/org/apache/commons/io/FilenameUtils.java
+++ b/src/main/java/org/apache/commons/io/FilenameUtils.java
@@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.commons.io;
import java.io.File;
@@ -28,30 +29,25 @@
import java.util.stream.Stream;
/**
- * General file name and file path manipulation utilities. The methods in this class
- * operate on strings that represent relative or absolute paths. Nothing in this class
- * ever accesses the file system, or depends on whether a path points to a file that exists.
+ * General file name and file path manipulation utilities. The methods in this class operate on strings that represent relative or absolute paths. Nothing in
+ * this class ever accesses the file system, or depends on whether a path points to a file that exists.
*
- * When dealing with file names, you can hit problems when moving from a Windows
- * based development machine to a Unix based production machine.
- * This class aims to help avoid those problems.
+ * When dealing with file names, you can hit problems when moving from a Windows based development machine to a Unix based production machine. This class aims
+ * to help avoid those problems.
*
*
- * NOTE: You may be able to avoid using this class entirely simply by
- * using JDK {@link File File} objects and the two argument constructor
+ * NOTE: You may be able to avoid using this class entirely simply by using JDK {@link File File} objects and the two argument constructor
* {@link File#File(java.io.File, String) File(File,String)}.
*
*
- * Most methods in this class are designed to work the same on both Unix and Windows.
- * Those that don't include 'System', 'Unix', or 'Windows' in their name.
+ * Most methods in this class are designed to work the same on both Unix and Windows. Those that don't include 'System', 'Unix', or 'Windows' in their name.
*
*
- * Most methods recognize both separators (forward and backslashes), and both
- * sets of prefixes. See the Javadoc of each method for details.
+ * Most methods recognize both separators (forward and backslashes), and both sets of prefixes. See the Javadoc of each method for details.
*
*
- * This class defines six components within a path (sometimes called a file name or a full file name).
- * Given an absolute Windows path such as C:\dev\project\file.txt they are:
+ * This class defines six components within a path (sometimes called a file name or a full file name). Given an absolute Windows path such as
+ * C:\dev\project\file.txt they are:
*
*
*
the full file name, or just file name - C:\dev\project\file.txt
@@ -98,18 +94,14 @@
*
the base name - file
*
the extension - txt
*
- *
- *
*
- * This class works best if directory names end with a separator.
- * If you omit the last separator, it is impossible to determine if the last component
- * corresponds to a file or a directory. This class treats final components
- * that do not end with a separator as files, not directories.
+ * This class works best if directory names end with a separator. If you omit the last separator, it is impossible to determine if the last component
+ * corresponds to a file or a directory. This class treats final components that do not end with a separator as files, not directories.
*
*
- * This class only supports Unix and Windows style names.
- * Prefixes are matched as follows:
+ * This class only supports Unix and Windows style names. Prefixes are matched as follows:
*
- * Both prefix styles are matched, irrespective of the machine that you are
- * currently running on.
+ * Both prefix styles are matched, irrespective of the machine that you are currently running on.
*
*
* @since 1.1
@@ -143,12 +134,14 @@ public class FilenameUtils {
/**
* The extension separator character.
+ *
* @since 1.4
*/
public static final char EXTENSION_SEPARATOR = '.';
/**
* The extension separator String.
+ *
* @since 1.4
*/
public static final String EXTENSION_SEPARATOR_STR = Character.toString(EXTENSION_SEPARATOR);
@@ -190,24 +183,20 @@ public class FilenameUtils {
/**
* Concatenates a fileName to a base path using normal command line style rules.
*
- * The effect is equivalent to resultant directory after changing
- * directory to the first argument, followed by changing directory to
- * the second argument.
+ * The effect is equivalent to resultant directory after changing directory to the first argument, followed by changing directory to the second argument.
*
*
- * The first argument is the base path, the second is the path to concatenate.
- * The returned path is always normalized via {@link #normalize(String)},
- * thus {@code ..} is handled.
+ * The first argument is the base path, the second is the path to concatenate. The returned path is always normalized via {@link #normalize(String)}, thus
+ * {@code ..} is handled.
*
*
- * If {@code pathToAdd} is absolute (has an absolute prefix), then
- * it will be normalized and returned.
- * Otherwise, the paths will be joined, normalized and returned.
+ * If {@code pathToAdd} is absolute (has an absolute prefix), then it will be normalized and returned. Otherwise, the paths will be joined, normalized and
+ * returned.
*
*
- * The output will be the same on both Unix and Windows except
- * for the separator character.
+ * The output will be the same on both Unix and Windows except for the separator character.
*
+ *
*
* /foo/ + bar --> /foo/bar
* /foo + bar --> /foo/bar
@@ -222,19 +211,17 @@ public class FilenameUtils {
* /foo/c.txt + bar --> /foo/c.txt/bar [2]
*
*
- * [1] Note that the Windows relative drive prefix is unreliable when
- * used with this method.
+ * [1] Note that the Windows relative drive prefix is unreliable when used with this method.
*
*
- * [2] Note that the first parameter must be a path. If it ends with a name, then
- * the name will be built into the concatenated path. If this might be a problem,
- * use {@link #getFullPath(String)} on the base path argument.
+ * [2] Note that the first parameter must be a path. If it ends with a name, then the name will be built into the concatenated path. If this might be a
+ * problem, use {@link #getFullPath(String)} on the base path argument.
*
*
- * @param basePath the base path to attach to, always treated as a path
- * @param fullFileNameToAdd the file name (or path) to attach to the base
- * @return the concatenated path, or null if invalid
- * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000})
+ * @param basePath The base path to attach to, always treated as a path.
+ * @param fullFileNameToAdd The file name (or path) to attach to the base.
+ * @return The concatenated path, or null if invalid.
+ * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000}).
*/
public static String concat(final String basePath, final String fullFileNameToAdd) {
final int prefix = getPrefixLength(fullFileNameToAdd);
@@ -259,13 +246,11 @@ public static String concat(final String basePath, final String fullFileNameToAd
}
/**
- * Determines whether the {@code parent} directory contains the {@code child} (a file or directory).
- * This does not read from the file system, and there is no guarantee or expectation that
- * these paths actually exist.
+ * Determines whether the {@code parent} directory contains the {@code child} (a file or directory). This does not read from the file system, and there is
+ * no guarantee or expectation that these paths actually exist.
*
* The files names are expected to be normalized.
*
- *
* Edge cases:
*
*
A {@code directory} must not be null: if null, throw IllegalArgumentException
@@ -273,36 +258,30 @@ public static String concat(final String basePath, final String fullFileNameToAd
*
A null child file is not contained in any parent: return false
*
*
- * @param canonicalParent the path string to consider as the parent.
- * @param canonicalChild the path string to consider as the child.
+ * @param canonicalParent The path string to consider as the parent.
+ * @param canonicalChild The path string to consider as the child.
* @return true if the candidate leaf is under the specified composite. False otherwise.
* @since 2.2
* @see FileUtils#directoryContains(File, File)
*/
public static boolean directoryContains(final String canonicalParent, final String canonicalChild) {
- if (isEmpty(canonicalParent) || isEmpty(canonicalChild)) {
+ if (isEmpty(canonicalParent) || isEmpty(canonicalChild) || IOCase.SYSTEM.checkEquals(canonicalParent, canonicalChild)) {
return false;
}
-
- if (IOCase.SYSTEM.checkEquals(canonicalParent, canonicalChild)) {
- return false;
- }
-
final char separator = toSeparator(canonicalParent.charAt(0) == UNIX_NAME_SEPARATOR);
final String parentWithEndSeparator = canonicalParent.charAt(canonicalParent.length() - 1) == separator ? canonicalParent : canonicalParent + separator;
-
return IOCase.SYSTEM.checkStartsWith(canonicalChild, parentWithEndSeparator);
}
/**
* Does the work of getting the path.
*
- * @param fileName the file name
- * @param includeSeparator true to include the end separator
- * @return the path
- * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000})
+ * @param fileName The file name.
+ * @param includeEndSeparator true to include the end separator.
+ * @return The path.
+ * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000}).
*/
- private static String doGetFullPath(final String fileName, final boolean includeSeparator) {
+ private static String doGetFullPath(final String fileName, final boolean includeEndSeparator) {
if (fileName == null) {
return null;
}
@@ -311,8 +290,8 @@ private static String doGetFullPath(final String fileName, final boolean include
return null;
}
if (prefix >= fileName.length()) {
- if (includeSeparator) {
- return getPrefix(fileName); // add end slash if necessary
+ if (includeEndSeparator) {
+ return getPrefix(fileName); // add end slash if necessary
}
return fileName;
}
@@ -320,7 +299,7 @@ private static String doGetFullPath(final String fileName, final boolean include
if (index < 0) {
return fileName.substring(0, prefix);
}
- int end = index + (includeSeparator ? 1 : 0);
+ int end = index + (includeEndSeparator ? 1 : 0);
if (end == 0) {
end++;
}
@@ -330,10 +309,10 @@ private static String doGetFullPath(final String fileName, final boolean include
/**
* Does the work of getting the path.
*
- * @param fileName the file name
- * @param separatorAdd 0 to omit the end separator, 1 to return it
- * @return the path
- * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000})
+ * @param fileName The file name.
+ * @param separatorAdd 0 to omit the end separator, 1 to return it.
+ * @return The path.
+ * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000}).
*/
private static String doGetPath(final String fileName, final int separatorAdd) {
if (fileName == null) {
@@ -354,19 +333,17 @@ private static String doGetPath(final String fileName, final int separatorAdd) {
/**
* Internal method to perform the normalization.
*
- * @param fileName the file name
- * @param separator The separator character to use
- * @param keepSeparator true to keep the final separator
- * @return the normalized fileName
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * @param fileName The file name.
+ * @param separator The separator character to use.
+ * @param keepSeparator true to keep the final separator.
+ * @return The normalized fileName.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
*/
private static String doNormalize(final String fileName, final char separator, final boolean keepSeparator) {
if (fileName == null) {
return null;
}
-
requireNonNullChars(fileName);
-
int size = fileName.length();
if (size == 0) {
return fileName;
@@ -375,10 +352,8 @@ private static String doNormalize(final String fileName, final char separator, f
if (prefix < 0) {
return null;
}
-
- final char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy
+ final char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy
fileName.getChars(0, fileName.length(), array, 0);
-
// fix separators throughout
final char otherSeparator = flipSeparator(separator);
for (int i = 0; i < array.length; i++) {
@@ -386,14 +361,12 @@ private static String doNormalize(final String fileName, final char separator, f
array[i] = separator;
}
}
-
// add extra separator on the end to simplify code below
boolean lastIsDirectory = true;
if (array[size - 1] != separator) {
array[size++] = separator;
lastIsDirectory = false;
}
-
// adjoining slashes
// If we get here, prefix can only be 0 or greater, size 1 or greater
// If prefix is 0, set loop start to 1 to prevent index errors
@@ -404,11 +377,9 @@ private static String doNormalize(final String fileName, final char separator, f
i--;
}
}
-
// period slash
for (int i = prefix + 1; i < size; i++) {
- if (array[i] == separator && array[i - 1] == '.' &&
- (i == prefix + 1 || array[i - 2] == separator)) {
+ if (array[i] == separator && array[i - 1] == '.' && (i == prefix + 1 || array[i - 2] == separator)) {
if (i == size - 1) {
lastIsDirectory = true;
}
@@ -417,12 +388,9 @@ private static String doNormalize(final String fileName, final char separator, f
i--;
}
}
-
// double period slash
- outer:
- for (int i = prefix + 2; i < size; i++) {
- if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' &&
- (i == prefix + 2 || array[i - 3] == separator)) {
+ outer: for (int i = prefix + 2; i < size; i++) {
+ if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' && (i == prefix + 2 || array[i - 3] == separator)) {
if (i == prefix + 2) {
return null;
}
@@ -430,7 +398,7 @@ private static String doNormalize(final String fileName, final char separator, f
lastIsDirectory = true;
}
int j;
- for (j = i - 4 ; j >= prefix; j--) {
+ for (j = i - 4; j >= prefix; j--) {
if (array[j] == separator) {
// remove b/../ from a/b/../c
System.arraycopy(array, i + 1, array, j + 1, size - i);
@@ -445,29 +413,24 @@ private static String doNormalize(final String fileName, final char separator, f
i = prefix + 1;
}
}
-
- if (size <= 0) { // should never be less than 0
+ if (size <= 0) { // should never be less than 0
return EMPTY_STRING;
}
- if (size <= prefix) { // should never be less than prefix
- return new String(array, 0, size);
+ if (size <= prefix || lastIsDirectory && keepSeparator) {
+ return new String(array, 0, size); // keep trailing separator
}
- if (lastIsDirectory && keepSeparator) {
- return new String(array, 0, size); // keep trailing separator
- }
- return new String(array, 0, size - 1); // lose trailing separator
+ return new String(array, 0, size - 1); // lose trailing separator
}
/**
* Checks whether two file names are exactly equal.
*
- * No processing is performed on the file names other than comparison.
- * This is merely a null-safe case-sensitive string equality.
+ * No processing is performed on the file names other than comparison. This is merely a null-safe case-sensitive string equality.
*
*
- * @param fileName1 the first file name, may be null
- * @param fileName2 the second file name, may be null
- * @return true if the file names are equal, null equals null
+ * @param fileName1 The first file name, may be null.
+ * @param fileName2 The second file name, may be null.
+ * @return true if the file names are equal, null equals null.
* @see IOCase#SENSITIVE
*/
public static boolean equals(final String fileName1, final String fileName2) {
@@ -475,18 +438,16 @@ public static boolean equals(final String fileName1, final String fileName2) {
}
/**
- * Checks whether two file names are equal, optionally normalizing and providing
- * control over the case-sensitivity.
- *
- * @param fileName1 the first file name, may be null
- * @param fileName2 the second file name, may be null
- * @param normalize whether to normalize the file names
- * @param ioCase what case sensitivity rule to use, null means case-sensitive
- * @return true if the file names are equal, null equals null
+ * Checks whether two file names are equal, optionally normalizing and providing control over the case-sensitivity.
+ *
+ * @param fileName1 The first file name, may be null.
+ * @param fileName2 The second file name, may be null.
+ * @param normalize whether to normalize the file names.
+ * @param ioCase what case sensitivity rule to use, null means case-sensitive.
+ * @return true if the file names are equal, null equals null.
* @since 1.3
*/
public static boolean equals(String fileName1, String fileName2, final boolean normalize, final IOCase ioCase) {
-
if (fileName1 == null || fileName2 == null) {
return fileName1 == null && fileName2 == null;
}
@@ -506,13 +467,12 @@ public static boolean equals(String fileName1, String fileName2, final boolean n
/**
* Checks whether two file names are equal after both have been normalized.
*
- * Both file names are first passed to {@link #normalize(String)}.
- * The check is then performed in a case-sensitive manner.
+ * Both file names are first passed to {@link #normalize(String)}. The check is then performed in a case-sensitive manner.
*
*
- * @param fileName1 the first file name, may be null
- * @param fileName2 the second file name, may be null
- * @return true if the file names are equal, null equals null
+ * @param fileName1 The first file name, may be null.
+ * @param fileName2 The second file name, may be null.
+ * @return true if the file names are equal, null equals null.
* @see IOCase#SENSITIVE
*/
public static boolean equalsNormalized(final String fileName1, final String fileName2) {
@@ -520,17 +480,14 @@ public static boolean equalsNormalized(final String fileName1, final String file
}
/**
- * Checks whether two file names are equal using the case rules of the system
- * after both have been normalized.
+ * Checks whether two file names are equal using the case rules of the system after both have been normalized.
*
- * Both file names are first passed to {@link #normalize(String)}.
- * The check is then performed case-sensitively on Unix and
- * case-insensitively on Windows.
+ * Both file names are first passed to {@link #normalize(String)}. The check is then performed case-sensitively on Unix and case-insensitively on Windows.
*
*
- * @param fileName1 the first file name, may be null
- * @param fileName2 the second file name, may be null
- * @return true if the file names are equal, null equals null
+ * @param fileName1 The first file name, may be null.
+ * @param fileName2 The second file name, may be null.
+ * @return true if the file names are equal, null equals null.
* @see IOCase#SYSTEM
*/
public static boolean equalsNormalizedOnSystem(final String fileName1, final String fileName2) {
@@ -540,13 +497,12 @@ public static boolean equalsNormalizedOnSystem(final String fileName1, final Str
/**
* Checks whether two file names are equal using the case rules of the system.
*
- * No processing is performed on the file names other than comparison.
- * The check is case-sensitive on Unix and case-insensitive on Windows.
+ * No processing is performed on the file names other than comparison. The check is case-sensitive on Unix and case-insensitive on Windows.
*
*
- * @param fileName1 the first file name, may be null
- * @param fileName2 the second file name, may be null
- * @return true if the file names are equal, null equals null
+ * @param fileName1 The first file name, may be null.
+ * @param fileName2 The second file name, may be null.
+ * @return true if the file names are equal, null equals null.
* @see IOCase#SYSTEM
*/
public static boolean equalsOnSystem(final String fileName1, final String fileName2) {
@@ -572,7 +528,7 @@ static char flipSeparator(final char ch) {
/**
* Special handling for NTFS ADS: Don't accept colon in the file name.
*
- * @param fileName a file name
+ * @param fileName A file name.
* @return ADS offsets.
*/
private static int getAdsCriticalOffset(final String fileName) {
@@ -594,9 +550,9 @@ private static int getAdsCriticalOffset(final String fileName) {
/**
* Gets the base name, minus the full path and extension, from a full file name.
*
- * This method will handle a path in either Unix or Windows format.
- * The text after the last forward or backslash and before the last period is returned.
+ * This method will handle a path in either Unix or Windows format. The text after the last forward or backslash and before the last period is returned.
*
+ *
*
* a/b/c.txt --> c
* a\b\c.txt --> c
@@ -609,9 +565,9 @@ private static int getAdsCriticalOffset(final String fileName) {
* The output will be the same irrespective of the machine that the code is running on.
*
*
- * @param fileName the file name, null returns null
- * @return the name of the file without the path, or an empty string if none exists
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * @param fileName The file name, null returns null.
+ * @return The name of the file without the path, or an empty string if none exists.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
*/
public static String getBaseName(final String fileName) {
return removeExtension(getName(fileName));
@@ -620,9 +576,9 @@ public static String getBaseName(final String fileName) {
/**
* Gets the extension of a file name.
*
- * This method returns the textual part of the file name after the last period.
- * There must be no directory separator after the period.
+ * This method returns the textual part of the file name after the last period. There must be no directory separator after the period.
*
- * The output will be the same irrespective of the machine that the code is running on, with the
- * exception of a possible {@link IllegalArgumentException} on Windows (see below).
+ * The output will be the same irrespective of the machine that the code is running on, with the exception of a possible {@link IllegalArgumentException} on
+ * Windows (see below).
*
*
- * Note: This method used to have a hidden problem for names like "foo.exe:bar.txt".
- * In this case, the name wouldn't be the name of a file, but the identifier of an
- * alternate data stream (bar.txt) on the file foo.exe. The method used to return
- * ".txt" here, which would be misleading. Commons IO 2.7 and later throw
- * an {@link IllegalArgumentException} for names like this.
+ * Note: This method used to have a hidden problem for names like "foo.exe:bar.txt". In this case, the name wouldn't be the name of a file,
+ * but the identifier of an alternate data stream (bar.txt) on the file foo.exe. The method used to return ".txt" here, which would be misleading. Commons
+ * IO 2.7 and later throw an {@link IllegalArgumentException} for names like this.
*
*
- * @param fileName the file name to retrieve the extension of.
- * @return the extension of the file or an empty string if none exists or {@code null}
- * if the file name is {@code null}.
- * @throws IllegalArgumentException Windows only: the file name parameter is, in fact,
- * the identifier of an Alternate Data Stream, for example "foo.exe:bar.txt".
+ * @param fileName The file name to retrieve the extension of.
+ * @return The extension of the file or an empty string if none exists or {@code null} if the file name is {@code null}.
+ * @throws IllegalArgumentException Windows only: the file name parameter is, in fact, the identifier of an Alternate Data Stream, for
+ * example "foo.exe:bar.txt".
*/
public static String getExtension(final String fileName) throws IllegalArgumentException {
if (fileName == null) {
@@ -661,10 +614,10 @@ public static String getExtension(final String fileName) throws IllegalArgumentE
/**
* Gets the full path (prefix + path) from a full file name.
*
- * This method will handle a file in either Unix or Windows format.
- * The method is entirely text based, and returns the text before and
- * including the last forward or backslash.
+ * This method will handle a file in either Unix or Windows format. The method is entirely text based, and returns the text before and including the last
+ * forward or backslash.
*
+ *
*
* C:\a\b\c.txt --> C:\a\b\
* ~/a/b/c.txt --> ~/a/b/
@@ -682,22 +635,21 @@ public static String getExtension(final String fileName) throws IllegalArgumentE
* The output will be the same irrespective of the machine that the code is running on.
*
*
- * @param fileName the file name, null returns null
- * @return the path of the file, an empty string if none exists, null if invalid
- * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000})
+ * @param fileName The file name, null returns null.
+ * @return The path of the file, an empty string if none exists, null if invalid.
+ * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000}).
*/
public static String getFullPath(final String fileName) {
return doGetFullPath(fileName, true);
}
/**
- * Gets the full path (prefix + path) from a full file name,
- * excluding the final directory separator.
+ * Gets the full path (prefix + path) from a full file name, excluding the final directory separator.
*
- * This method will handle a file in either Unix or Windows format.
- * The method is entirely text based, and returns the text before the
- * last forward or backslash.
+ * This method will handle a file in either Unix or Windows format. The method is entirely text based, and returns the text before the last forward or
+ * backslash.
*
+ *
*
* C:\a\b\c.txt --> C:\a\b
* ~/a/b/c.txt --> ~/a/b
@@ -715,9 +667,9 @@ public static String getFullPath(final String fileName) {
* The output will be the same irrespective of the machine that the code is running on.
*
*
- * @param fileName the file name, null returns null
- * @return the path of the file, an empty string if none exists, null if invalid
- * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000})
+ * @param fileName The file name, null returns null.
+ * @return The path of the file, an empty string if none exists, null if invalid.
+ * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000}).
*/
public static String getFullPathNoEndSeparator(final String fileName) {
return doGetFullPath(fileName, false);
@@ -726,9 +678,9 @@ public static String getFullPathNoEndSeparator(final String fileName) {
/**
* Gets the name minus the path from a full file name.
*
- * This method will handle a file in either Unix or Windows format.
- * The text after the last forward or backslash is returned.
+ * This method will handle a file in either Unix or Windows format. The text after the last forward or backslash is returned.
*
+ *
*
* a/b/c.txt --> c.txt
* a\b\c.txt --> c.txt
@@ -740,9 +692,9 @@ public static String getFullPathNoEndSeparator(final String fileName) {
* The output will be the same irrespective of the machine that the code is running on.
*
*
- * @param fileName the file name, null returns null
- * @return the name of the file without the path, or an empty string if none exists
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * @param fileName The file name, null returns null.
+ * @return The name of the file without the path, or an empty string if none exists.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
*/
public static String getName(final String fileName) {
if (fileName == null) {
@@ -754,10 +706,10 @@ public static String getName(final String fileName) {
/**
* Gets the path from a full file name, which excludes the prefix and the name.
*
- * This method will handle a file in either Unix or Windows format.
- * The method is entirely text based, and returns the text before and
- * including the last forward or backslash.
+ * This method will handle a file in either Unix or Windows format. The method is entirely text based, and returns the text before and including the last
+ * forward or backslash.
*
+ *
*
* C:\a\b\c.txt --> a\b\
* ~/a/b/c.txt --> a/b/
@@ -769,26 +721,24 @@ public static String getName(final String fileName) {
* The output will be the same irrespective of the machine that the code is running on.
*
*
- * This method drops the prefix from the result.
- * See {@link #getFullPath(String)} for the method that retains the prefix.
+ * This method drops the prefix from the result. See {@link #getFullPath(String)} for the method that retains the prefix.
*
*
- * @param fileName the file name, null returns null
- * @return the path of the file, an empty string if none exists, null if invalid
- * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000})
+ * @param fileName The file name, null returns null.
+ * @return The path of the file, an empty string if none exists, null if invalid.
+ * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000}).
*/
public static String getPath(final String fileName) {
return doGetPath(fileName, 1);
}
/**
- * Gets the path (which excludes the prefix) from a full file name, and
- * also excluding the final directory separator.
+ * Gets the path (which excludes the prefix) from a full file name, and also excluding the final directory separator.
*
- * This method will handle a file in either Unix or Windows format.
- * The method is entirely text based, and returns the text before the
- * last forward or backslash.
+ * This method will handle a file in either Unix or Windows format. The method is entirely text based, and returns the text before the last forward or
+ * backslash.
*
+ *
*
* C:\a\b\c.txt --> a\b
* ~/a/b/c.txt --> a/b
@@ -800,13 +750,12 @@ public static String getPath(final String fileName) {
* The output will be the same irrespective of the machine that the code is running on.
*
*
- * This method drops the prefix from the result.
- * See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix.
+ * This method drops the prefix from the result. See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix.
*
*
- * @param fileName the file name, null returns null
- * @return the path of the file, an empty string if none exists, null if invalid
- * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000})
+ * @param fileName The file name, null returns null.
+ * @return The path of the file, an empty string if none exists, null if invalid.
+ * @throws IllegalArgumentException if the result path contains the null character ({@code U+0000}).
*/
public static String getPathNoEndSeparator(final String fileName) {
return doGetPath(fileName, 0);
@@ -815,9 +764,9 @@ public static String getPathNoEndSeparator(final String fileName) {
/**
* Gets the prefix such as {@code C:/} or {@code ~/} from a full file name,
*
- * This method will handle a file in either Unix or Windows format.
- * The prefix includes the first slash in the full file name where applicable.
+ * This method will handle a file in either Unix or Windows format. The prefix includes the first slash in the full file name where applicable.
*
+ *
*
* Windows:
* a\b\c.txt --> "" --> relative
@@ -835,13 +784,12 @@ public static String getPathNoEndSeparator(final String fileName) {
* ~user --> "~user/" --> named user (slash added)
*
*
- * The output will be the same irrespective of the machine that the code is running on.
- * ie. both Unix and Windows prefixes are matched regardless.
+ * The output will be the same irrespective of the machine that the code is running on. ie. both Unix and Windows prefixes are matched regardless.
*
*
- * @param fileName the file name, null returns null
- * @return the prefix of the file, null if invalid
- * @throws IllegalArgumentException if the result contains the null character ({@code U+0000})
+ * @param fileName The file name, null returns null.
+ * @return The prefix of the file, null if invalid.
+ * @throws IllegalArgumentException if the result contains the null character ({@code U+0000}).
*/
public static String getPrefix(final String fileName) {
if (fileName == null) {
@@ -864,10 +812,10 @@ public static String getPrefix(final String fileName) {
* This method will handle a file in either Unix or Windows format.
*
*
- * The prefix length includes the first slash in the full file name
- * if applicable. Thus, it is possible that the length returned is greater
- * than the length of the input string.
+ * The prefix length includes the first slash in the full file name if applicable. Thus, it is possible that the length returned is greater than the length
+ * of the input string.
*
+ *
*
* Windows:
* a\b\c.txt --> 0 --> relative
@@ -889,17 +837,15 @@ public static String getPrefix(final String fileName) {
* C: --> 0 --> valid file name as only null character and / are reserved characters
*
*
- * The output will be the same irrespective of the machine that the code is running on.
- * ie. both Unix and Windows prefixes are matched regardless.
+ * The output will be the same irrespective of the machine that the code is running on. ie. both Unix and Windows prefixes are matched regardless.
*
*
- * Note that a leading // (or \\) is used to indicate a UNC name on Windows.
- * These must be followed by a server name, so double-slashes are not collapsed
- * to a single slash at the start of the file name.
+ * Note that a leading // (or \\) is used to indicate a UNC name on Windows. These must be followed by a server name, so double-slashes are not collapsed to
+ * a single slash at the start of the file name.
*
*
- * @param fileName the file name to find the prefix in, null returns -1
- * @return the length of the prefix, -1 if invalid or null
+ * @param fileName The file name to find the prefix in, null returns -1.
+ * @return The length of the prefix, -1 if invalid or null.
*/
public static int getPrefixLength(final String fileName) {
if (fileName == null) {
@@ -915,7 +861,7 @@ public static int getPrefixLength(final String fileName) {
}
if (len == 1) {
if (ch0 == '~') {
- return 2; // return a length greater than the input
+ return 2; // return a length greater than the input
}
return isSeparator(ch0) ? 1 : 0;
}
@@ -923,7 +869,7 @@ public static int getPrefixLength(final String fileName) {
int posUnix = fileName.indexOf(UNIX_NAME_SEPARATOR, 1);
int posWin = fileName.indexOf(WINDOWS_NAME_SEPARATOR, 1);
if (posUnix == NOT_FOUND && posWin == NOT_FOUND) {
- return len + 1; // return a length greater than the input
+ return len + 1; // return a length greater than the input
}
posUnix = posUnix == NOT_FOUND ? posWin : posUnix;
posWin = posWin == NOT_FOUND ? posUnix : posWin;
@@ -945,7 +891,6 @@ public static int getPrefixLength(final String fileName) {
return 1;
}
return NOT_FOUND;
-
}
if (!isSeparator(ch0) || !isSeparator(ch1)) {
return isSeparator(ch0) ? 1 : 0;
@@ -965,24 +910,23 @@ public static int getPrefixLength(final String fileName) {
/**
* Returns the index of the last extension separator character, which is a period.
*
- * This method also checks that there is no directory separator after the last period. To do this it uses
- * {@link #indexOfLastSeparator(String)} which will handle a file in either Unix or Windows format.
+ * This method also checks that there is no directory separator after the last period. To do this it uses {@link #indexOfLastSeparator(String)} which will
+ * handle a file in either Unix or Windows format.
*
*
- * The output will be the same irrespective of the machine that the code is running on, with the
- * exception of a possible {@link IllegalArgumentException} on Windows (see below).
+ * The output will be the same irrespective of the machine that the code is running on, with the exception of a possible {@link IllegalArgumentException} on
+ * Windows (see below).
*
- * Note: This method used to have a hidden problem for names like "foo.exe:bar.txt".
- * In this case, the name wouldn't be the name of a file, but the identifier of an
- * alternate data stream (bar.txt) on the file foo.exe. The method used to return
- * ".txt" here, which would be misleading. Commons IO 2.7, and later versions, are throwing
- * an {@link IllegalArgumentException} for names like this.
- *
- * @param fileName
- * the file name to find the last extension separator in, null returns -1
- * @return the index of the last extension separator character, or -1 if there is no such character
- * @throws IllegalArgumentException Windows only: the file name parameter is, in fact,
- * the identifier of an Alternate Data Stream, for example "foo.exe:bar.txt".
+ *
+ * Note: This method used to have a hidden problem for names like "foo.exe:bar.txt". In this case, the name wouldn't be the name of a file,
+ * but the identifier of an alternate data stream (bar.txt) on the file foo.exe. The method used to return ".txt" here, which would be misleading. Commons
+ * IO 2.7, and later versions, are throwing an {@link IllegalArgumentException} for names like this.
+ *
+ *
+ * @param fileName The file name to find the last extension separator in, null returns -1.
+ * @return The index of the last extension separator character, or -1 if there is no such character.
+ * @throws IllegalArgumentException Windows only: the file name parameter is, in fact, the identifier of an Alternate Data Stream, for
+ * example "foo.exe:bar.txt".
*/
public static int indexOfExtension(final String fileName) throws IllegalArgumentException {
if (fileName == null) {
@@ -1003,14 +947,14 @@ public static int indexOfExtension(final String fileName) throws IllegalArgument
/**
* Returns the index of the last directory separator character.
*
- * This method will handle a file in either Unix or Windows format.
- * The position of the last forward or backslash is returned.
+ * This method will handle a file in either Unix or Windows format. The position of the last forward or backslash is returned.
+ *
*
* The output will be the same irrespective of the machine that the code is running on.
+ *
*
- * @param fileName the file name to find the last path separator in, null returns -1
- * @return the index of the last separator character, or -1 if there
- * is no such character
+ * @param fileName The file name to find the last path separator in, null returns -1.
+ * @return The index of the last separator character, or -1 if there is no such character.
*/
public static int indexOfLastSeparator(final String fileName) {
if (fileName == null) {
@@ -1028,21 +972,20 @@ private static boolean isEmpty(final String string) {
/**
* Checks whether the extension of the file name is one of those specified.
*
- * This method obtains the extension as the textual part of the file name
- * after the last period. There must be no directory separator after the period.
- * The extension check is case-sensitive on all platforms.
- *
- * @param fileName the file name, null returns false
- * @param extensions the extensions to check for, null checks for no extension
- * @return true if the file name is one of the extensions
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * This method obtains the extension as the textual part of the file name after the last period. There must be no directory separator after the period. The
+ * extension check is case-sensitive on all platforms.
+ *
+ *
+ * @param fileName The file name, null returns false.
+ * @param extensions The extensions to check for, null checks for no extension.
+ * @return true if the file name is one of the extensions.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
*/
public static boolean isExtension(final String fileName, final Collection extensions) {
if (fileName == null) {
return false;
}
requireNonNullChars(fileName);
-
if (extensions == null || extensions.isEmpty()) {
return indexOfExtension(fileName) == NOT_FOUND;
}
@@ -1052,21 +995,20 @@ public static boolean isExtension(final String fileName, final Collection
- * This method obtains the extension as the textual part of the file name
- * after the last period. There must be no directory separator after the period.
- * The extension check is case-sensitive on all platforms.
- *
- * @param fileName the file name, null returns false
- * @param extension the extension to check for, null or empty checks for no extension
- * @return true if the file name has the specified extension
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * This method obtains the extension as the textual part of the file name after the last period. There must be no directory separator after the period. The
+ * extension check is case-sensitive on all platforms.
+ *
+ *
+ * @param fileName The file name, null returns false.
+ * @param extension The extension to check for, null or empty checks for no extension.
+ * @return true if the file name has the specified extension.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
*/
public static boolean isExtension(final String fileName, final String extension) {
if (fileName == null) {
return false;
}
requireNonNullChars(fileName);
-
if (isEmpty(extension)) {
return indexOfExtension(fileName) == NOT_FOUND;
}
@@ -1076,21 +1018,20 @@ public static boolean isExtension(final String fileName, final String extension)
/**
* Checks whether the extension of the file name is one of those specified.
*
- * This method obtains the extension as the textual part of the file name
- * after the last period. There must be no directory separator after the period.
- * The extension check is case-sensitive on all platforms.
- *
- * @param fileName the file name, null returns false
- * @param extensions the extensions to check for, null checks for no extension
- * @return true if the file name is one of the extensions
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * This method obtains the extension as the textual part of the file name after the last period. There must be no directory separator after the period. The
+ * extension check is case-sensitive on all platforms.
+ *
+ *
+ * @param fileName The file name, null returns false.
+ * @param extensions The extensions to check for, null checks for no extension.
+ * @return true if the file name is one of the extensions.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
*/
public static boolean isExtension(final String fileName, final String... extensions) {
if (fileName == null) {
return false;
}
requireNonNullChars(fileName);
-
if (extensions == null || extensions.length == 0) {
return indexOfExtension(fileName) == NOT_FOUND;
}
@@ -1101,8 +1042,8 @@ public static boolean isExtension(final String fileName, final String... extensi
/**
* Checks whether a given string represents a valid IPv4 address.
*
- * @param name the name to validate
- * @return true if the given name is a valid IPv4 address
+ * @param name The name to validate.
+ * @return true if the given name is a valid IPv4 address.
*/
// mostly copied from org.apache.commons.validator.routines.InetAddressValidator#isValidInet4Address
private static boolean isIPv4Address(final String name) {
@@ -1110,21 +1051,14 @@ private static boolean isIPv4Address(final String name) {
if (!m.matches() || m.groupCount() != 4) {
return false;
}
-
// verify that address subgroups are legal
for (int i = 1; i <= 4; i++) {
final String ipSegment = m.group(i);
final int iIpSegment = Integer.parseInt(ipSegment);
- if (iIpSegment > IPV4_MAX_OCTET_VALUE) {
- return false;
- }
-
- if (ipSegment.length() > 1 && ipSegment.startsWith("0")) {
+ if (iIpSegment > IPV4_MAX_OCTET_VALUE || ipSegment.length() > 1 && ipSegment.startsWith("0")) {
return false;
}
-
}
-
return true;
}
@@ -1132,16 +1066,15 @@ private static boolean isIPv4Address(final String name) {
/**
* Checks whether a given string represents a valid IPv6 address.
*
- * @param inet6Address the name to validate
- * @return true if the given name is a valid IPv6 address
+ * @param inet6Address The name to validate.
+ * @return true if the given name is a valid IPv6 address.
*/
private static boolean isIPv6Address(final String inet6Address) {
final boolean containsCompressedZeroes = inet6Address.contains("::");
if (containsCompressedZeroes && inet6Address.indexOf("::") != inet6Address.lastIndexOf("::")) {
return false;
}
- if (inet6Address.startsWith(":") && !inet6Address.startsWith("::")
- || inet6Address.endsWith(":") && !inet6Address.endsWith("::")) {
+ if (inet6Address.startsWith(":") && !inet6Address.startsWith("::") || inet6Address.endsWith(":") && !inet6Address.endsWith("::")) {
return false;
}
String[] octets = inet6Address.split(":");
@@ -1196,12 +1129,11 @@ private static boolean isIPv6Address(final String inet6Address) {
}
/**
- * Checks whether a given string is a valid host name according to
- * RFC 3986 - not accepting IP addresses.
+ * Checks whether a given string is a valid host name according to RFC 3986 - not accepting IP addresses.
*
* @see "https://tools.ietf.org/html/rfc3986#section-3.2.2"
- * @param name the hostname to validate
- * @return true if the given name is a valid host name
+ * @param name The hostname to validate.
+ * @return true if the given name is a valid host name.
*/
private static boolean isRFC3986HostName(final String name) {
final String[] parts = name.split("\\.", -1);
@@ -1220,8 +1152,8 @@ private static boolean isRFC3986HostName(final String name) {
/**
* Checks if the character is a separator.
*
- * @param ch the character to check
- * @return true if it is a separator character
+ * @param ch The character to check.
+ * @return true if it is a separator character.
*/
private static boolean isSeparator(final char ch) {
return ch == UNIX_NAME_SEPARATOR || ch == WINDOWS_NAME_SEPARATOR;
@@ -1230,23 +1162,21 @@ private static boolean isSeparator(final char ch) {
/**
* Determines if Windows file system is in use.
*
- * @return true if the system is Windows
+ * @return true if the system is Windows.
*/
static boolean isSystemWindows() {
return SYSTEM_NAME_SEPARATOR == WINDOWS_NAME_SEPARATOR;
}
/**
- * Checks whether a given string is a valid host name according to
- * RFC 3986.
- *
- *
Accepted are IP addresses (v4 and v6) as well as what the
- * RFC calls a "reg-name". Percent encoded names don't seem to be
- * valid names in UNC paths.
+ * Checks whether a given string is a valid host name according to RFC 3986.
+ *
+ * Accepted are IP addresses (v4 and v6) as well as what the RFC calls a "reg-name". Percent encoded names don't seem to be valid names in UNC paths.
+ *
*
* @see "https://tools.ietf.org/html/rfc3986#section-3.2.2"
- * @param name the hostname to validate
- * @return true if the given name is a valid host name
+ * @param name The hostname to validate.
+ * @return true if the given name is a valid host name.
*/
private static boolean isValidHostName(final String name) {
return isIPv6Address(name) || isRFC3986HostName(name);
@@ -1255,18 +1185,20 @@ private static boolean isValidHostName(final String name) {
/**
* Normalizes a path, removing double and single period path steps.
*
- * This method normalizes a path to a standard format.
- * The input may contain separators in either Unix or Windows format.
- * The output will contain separators in the format of the system.
- *
- * A trailing slash will be retained.
- * A double slash will be merged to a single slash (but UNC names are handled).
- * A single period path segment will be removed.
- * A double period will cause that path segment and the one before to be removed.
- * If the double period has no parent path segment, {@code null} is returned.
+ * This method normalizes a path to a standard format. The input may contain separators in either Unix or Windows format. The output will contain separators
+ * in the format of the system.
+ *
+ *
+ *
A trailing slash will be retained.
+ *
A double slash will be merged to a single slash (but UNC names are handled).
+ *
A single period path segment will be removed.
+ *
A double period will cause that path segment and the one before to be removed.
+ *
If the double period has no parent path segment, {@code null} is returned.
+ *
*
- * The output will be the same on both Unix and Windows except
- * for the separator character.
+ * The output will be the same on both Unix and Windows except for the separator character.
+ *
* (Note the file separator will be correct for Windows/Unix.)
+ *
*
- * @param fileName the file name to normalize, null returns null
- * @return the normalized fileName, or null if invalid
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * @param fileName The file name to normalize, null returns null.
+ * @return The normalized fileName, or null if invalid.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
*/
public static String normalize(final String fileName) {
return doNormalize(fileName, SYSTEM_NAME_SEPARATOR, true);
@@ -1299,19 +1233,20 @@ public static String normalize(final String fileName) {
/**
* Normalizes a path, removing double and single period path steps.
*
- * This method normalizes a path to a standard format.
- * The input may contain separators in either Unix or Windows format.
- * The output will contain separators in the format specified.
- *
- * A trailing slash will be retained.
- * A double slash will be merged to a single slash (but UNC names are handled).
- * A single period path segment will be removed.
- * A double period will cause that path segment and the one before to be removed.
- * If the double period has no parent path segment to work with, {@code null}
- * is returned.
+ * This method normalizes a path to a standard format. The input may contain separators in either Unix or Windows format. The output will contain separators
+ * in the format specified.
+ *
+ *
+ *
A trailing slash will be retained.
+ *
A double slash will be merged to a single slash (but UNC names are handled).
+ *
A single period path segment will be removed.
+ *
A double period will cause that path segment and the one before to be removed.
+ *
If the double period has no parent path segment to work with, {@code null} is returned.
+ *
*
- * The output will be the same on both Unix and Windows except
- * for the separator character.
+ * The output will be the same on both Unix and Windows except for the separator character.
+ *
- * The output will be the same on both Unix and Windows including
- * the separator character.
- *
- * @param fileName the file name to normalize, null returns null
- * @param unixSeparator {@code true} if a Unix separator should
- * be used or {@code false} if a Windows separator should be used.
- * @return the normalized fileName, or null if invalid
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ *
+ * The output will be the same on both Unix and Windows including the separator character.
+ *
+ *
+ * @param fileName The file name to normalize, null returns null.
+ * @param unixSeparator {@code true} if a Unix separator should be used or {@code false} if a Windows separator should be used.
+ * @return The normalized fileName, or null if invalid.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
* @since 2.0
*/
public static String normalize(final String fileName, final boolean unixSeparator) {
@@ -1346,22 +1281,22 @@ public static String normalize(final String fileName, final boolean unixSeparato
}
/**
- * Normalizes a path, removing double and single period path steps,
- * and removing any final directory separator.
- *
- * This method normalizes a path to a standard format.
- * The input may contain separators in either Unix or Windows format.
- * The output will contain separators in the format of the system.
+ * Normalizes a path, removing double and single period path steps, and removing any final directory separator.
*
- * A trailing slash will be removed.
- * A double slash will be merged to a single slash (but UNC names are handled).
- * A single period path segment will be removed.
- * A double period will cause that path segment and the one before to be removed.
- * If the double period has no parent path segment to work with, {@code null}
- * is returned.
+ * This method normalizes a path to a standard format. The input may contain separators in either Unix or Windows format. The output will contain separators
+ * in the format of the system.
+ *
+ *
+ *
A trailing slash will be removed.
+ *
A double slash will be merged to a single slash (but UNC names are handled).
+ *
A single period path segment will be removed.
+ *
A double period will cause that path segment and the one before to be removed.
+ *
If the double period has no parent path segment to work with, {@code null} is returned.
+ *
*
- * The output will be the same on both Unix and Windows except
- * for the separator character.
+ * The output will be the same on both Unix and Windows except for the separator character.
+ *
+ *
* (Note the file separator returned will be correct for Windows/Unix)
*
- * @param fileName the file name to normalize, null returns null
- * @return the normalized fileName, or null if invalid
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * @param fileName The file name to normalize, null returns null.
+ * @return The normalized fileName, or null if invalid.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
*/
public static String normalizeNoEndSeparator(final String fileName) {
return doNormalize(fileName, SYSTEM_NAME_SEPARATOR, false);
}
/**
- * Normalizes a path, removing double and single period path steps,
- * and removing any final directory separator.
- *
- * This method normalizes a path to a standard format.
- * The input may contain separators in either Unix or Windows format.
- * The output will contain separators in the format specified.
+ * Normalizes a path, removing double and single period path steps, and removing any final directory separator.
*
- * A trailing slash will be removed.
- * A double slash will be merged to a single slash (but UNC names are handled).
- * A single period path segment will be removed.
- * A double period will cause that path segment and the one before to be removed.
- * If the double period has no parent path segment to work with, {@code null}
- * is returned.
+ * This method normalizes a path to a standard format. The input may contain separators in either Unix or Windows format. The output will contain separators
+ * in the format specified.
+ *
+ *
+ *
A trailing slash will be removed.
+ *
A double slash will be merged to a single slash (but UNC names are handled).
+ *
A single period path segment will be removed.
+ *
A double period will cause that path segment and the one before to be removed.
+ *
If the double period has no parent path segment to work with, {@code null} is returned.
+ *
*
- * The output will be the same on both Unix and Windows including
- * the separator character.
+ * The output will be the same on both Unix and Windows including the separator character.
+ *
*
*
- * @param fileName the file name to normalize, null returns null
- * @param unixSeparator {@code true} if a Unix separator should
- * be used or {@code false} if a Windows separator should be used.
- * @return the normalized fileName, or null if invalid
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * @param fileName The file name to normalize, null returns null.
+ * @param unixSeparator {@code true} if a Unix separator should be used or {@code false} if a Windows separator should be used.
+ * @return The normalized fileName, or null if invalid.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
* @since 2.0
*/
public static String normalizeNoEndSeparator(final String fileName, final boolean unixSeparator) {
- return doNormalize(fileName, toSeparator(unixSeparator), false);
+ return doNormalize(fileName, toSeparator(unixSeparator), false);
}
/**
* Removes the extension from a fileName.
*
- * This method returns the textual part of the file name before the last period.
- * There must be no directory separator after the period.
+ * This method returns the textual part of the file name before the last period. There must be no directory separator after the period.
+ *
*
* The output will be the same irrespective of the machine that the code is running on.
*
- * @param fileName the file name, null returns null
- * @return the file name minus the extension
- * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000})
+ * @param fileName The file name, null returns null.
+ * @return The file name minus the extension.
+ * @throws IllegalArgumentException if the file name contains the null character ({@code U+0000}).
*/
public static String removeExtension(final String fileName) {
if (fileName == null) {
return null;
}
requireNonNullChars(fileName);
-
final int index = indexOfExtension(fileName);
if (index == NOT_FOUND) {
return fileName;
@@ -1473,18 +1406,17 @@ public static String removeExtension(final String fileName) {
}
/**
- * Checks the input for null characters ({@code U+0000}), a sign of unsanitized data being passed to file level functions.
+ * Checks the input for null characters ({@code U+0000}), a sign of unsanitized data being passed to file level functions. This may be used to defend
+ * against poison byte attacks.
*
- * This may be used to defend against poison byte attacks.
- *
- * @param path the path to check
- * @return The input
- * @throws IllegalArgumentException if path contains the null character ({@code U+0000})
+ * @param path The path to check.
+ * @return The input.
+ * @throws IllegalArgumentException if path contains the null character ({@code U+0000}).
*/
private static String requireNonNullChars(final String path) {
if (path.indexOf(0) >= 0) {
throw new IllegalArgumentException(
- "Null character present in file/path name. There are no known legitimate use cases for such data, but several injection attacks may use it");
+ "Null character present in file/path name; there are no legitimate use cases, but several injection attacks may use it");
}
return path;
}
@@ -1492,8 +1424,8 @@ private static String requireNonNullChars(final String path) {
/**
* Converts all separators to the system separator.
*
- * @param path the path to be changed, null ignored.
- * @return the updated path.
+ * @param path The path to be changed, null ignored.
+ * @return The updated path.
*/
public static String separatorsToSystem(final String path) {
return FileSystem.getCurrent().normalizeSeparators(path);
@@ -1502,8 +1434,8 @@ public static String separatorsToSystem(final String path) {
/**
* Converts all separators to the Unix separator of forward slash.
*
- * @param path the path to be changed, null ignored.
- * @return the new path.
+ * @param path The path to be changed, null ignored.
+ * @return The new path.
*/
public static String separatorsToUnix(final String path) {
return FileSystem.LINUX.normalizeSeparators(path);
@@ -1512,29 +1444,25 @@ public static String separatorsToUnix(final String path) {
/**
* Converts all separators to the Windows separator of backslash.
*
- * @param path the path to be changed, null ignored.
- * @return the updated path.
+ * @param path The path to be changed, null ignored.
+ * @return The updated path.
*/
public static String separatorsToWindows(final String path) {
return FileSystem.WINDOWS.normalizeSeparators(path);
}
/**
- * Splits a string into a number of tokens.
- * The text is split by '?' and '*'.
- * Where multiple '*' occur consecutively they are collapsed into a single '*'.
+ * Splits a string into a number of tokens. The text is split by '?' and '*'. Where multiple '*' occur consecutively they are collapsed into a single '*'.
*
- * @param text the text to split
- * @return the array of tokens, never null
+ * @param text The text to split.
+ * @return The array of tokens, never null.
*/
static String[] splitOnTokens(final String text) {
// used by wildcardMatch
// package level so a unit test may run on this
-
if (text.indexOf('?') == NOT_FOUND && text.indexOf('*') == NOT_FOUND) {
return new String[] { text };
}
-
final char[] array = text.toCharArray();
final ArrayList list = new ArrayList<>();
final StringBuilder buffer = new StringBuilder();
@@ -1558,7 +1486,6 @@ static String[] splitOnTokens(final String text) {
if (buffer.length() != 0) {
list.add(buffer.toString());
}
-
return list.toArray(EMPTY_STRING_ARRAY);
}
@@ -1573,13 +1500,12 @@ private static char toSeparator(final boolean unixSeparator) {
}
/**
- * Checks a fileName to see if it matches the specified wildcard matcher,
- * always testing case-sensitive.
+ * Checks a fileName to see if it matches the specified wildcard matcher, always testing case-sensitive.
*
- * The wildcard matcher uses the characters '?' and '*' to represent a
- * single or multiple (zero or more) wildcard characters.
- * This is the same as often found on DOS/Unix command lines.
- * The check is case-sensitive always.
+ * The wildcard matcher uses the characters '?' and '*' to represent a single or multiple (zero or more) wildcard characters. This is the same as often
+ * found on DOS/Unix command lines. The check is case-sensitive always.
+ *
* The sequence "*?" does not work properly at present in match strings.
+ *
*
- * @param fileName the file name to match on
- * @param wildcardMatcher the wildcard string to match against
- * @return true if the file name matches the wildcard string
+ * @param fileName The file name to match on, may be null.
+ * @param wildcardMatcher The wildcard string to match against, may be null.
+ * @return true if the file name matches the wildcard string.
* @see IOCase#SENSITIVE
*/
public static boolean wildcardMatch(final String fileName, final String wildcardMatcher) {
@@ -1599,17 +1527,16 @@ public static boolean wildcardMatch(final String fileName, final String wildcard
}
/**
- * Checks a fileName to see if it matches the specified wildcard matcher
- * allowing control over case-sensitivity.
+ * Checks a fileName to see if it matches the specified wildcard matcher allowing control over case-sensitivity.
*
- * The wildcard matcher uses the characters '?' and '*' to represent a
- * single or multiple (zero or more) wildcard characters.
- * The sequence "*?" does not work properly at present in match strings.
+ * The wildcard matcher uses the characters '?' and '*' to represent a single or multiple (zero or more) wildcard characters. The sequence "*?" does not
+ * work properly at present in match strings.
+ *
*
- * @param fileName the file name to match on
- * @param wildcardMatcher the wildcard string to match against
- * @param ioCase what case sensitivity rule to use, null means case-sensitive
- * @return true if the file name matches the wildcard string
+ * @param fileName The file name to match on, may be null.
+ * @param wildcardMatcher The wildcard string to match against, may be null.
+ * @param ioCase what case sensitivity rule to use, null means case-sensitive.
+ * @return true if the file name matches the wildcard string.
* @since 1.3
*/
public static boolean wildcardMatch(final String fileName, final String wildcardMatcher, IOCase ioCase) {
@@ -1625,7 +1552,6 @@ public static boolean wildcardMatch(final String fileName, final String wildcard
int textIdx = 0;
int wcsIdx = 0;
final Deque backtrack = new ArrayDeque<>(wcs.length);
-
// loop around a backtrack stack, to handle complex * matching
do {
if (!backtrack.isEmpty()) {
@@ -1634,10 +1560,8 @@ public static boolean wildcardMatch(final String fileName, final String wildcard
textIdx = array[1];
anyChars = true;
}
-
// loop whilst tokens and text left to process
while (wcsIdx < wcs.length) {
-
if (wcs[wcsIdx].equals("?")) {
// ? so move to next text char
textIdx++;
@@ -1645,14 +1569,12 @@ public static boolean wildcardMatch(final String fileName, final String wildcard
break;
}
anyChars = false;
-
} else if (wcs[wcsIdx].equals("*")) {
// set any chars status
anyChars = true;
if (wcsIdx == wcs.length - 1) {
textIdx = fileName.length();
}
-
} else {
// matching text token
if (anyChars) {
@@ -1664,40 +1586,34 @@ public static boolean wildcardMatch(final String fileName, final String wildcard
}
final int repeat = ioCase.checkIndexOf(fileName, textIdx + 1, wcs[wcsIdx]);
if (repeat >= 0) {
- backtrack.push(new int[] {wcsIdx, repeat});
+ backtrack.push(new int[] { wcsIdx, repeat });
}
} else if (!ioCase.checkRegionMatches(fileName, textIdx, wcs[wcsIdx])) {
// matching from current position
// couldn't match token
break;
}
-
// matched text token, move text index to end of matched token
textIdx += wcs[wcsIdx].length();
anyChars = false;
}
-
wcsIdx++;
}
-
// full match
if (wcsIdx == wcs.length && textIdx == fileName.length()) {
return true;
}
-
} while (!backtrack.isEmpty());
-
return false;
}
/**
- * Checks a fileName to see if it matches the specified wildcard matcher
- * using the case rules of the system.
+ * Checks a fileName to see if it matches the specified wildcard matcher using the case rules of the system.
*
- * The wildcard matcher uses the characters '?' and '*' to represent a
- * single or multiple (zero or more) wildcard characters.
- * This is the same as often found on DOS/Unix command lines.
- * The check is case-sensitive on Unix and case-insensitive on Windows.
+ * The wildcard matcher uses the characters '?' and '*' to represent a single or multiple (zero or more) wildcard characters. This is the same as often
+ * found on DOS/Unix command lines. The check is case-sensitive on Unix and case-insensitive on Windows.
+ *
* The sequence "*?" does not work properly at present in match strings.
+ *
*
- * @param fileName the file name to match on
- * @param wildcardMatcher the wildcard string to match against
- * @return true if the file name matches the wildcard string
+ * @param fileName The file name to match on.
+ * @param wildcardMatcher The wildcard string to match against.
+ * @return true if the file name matches the wildcard string.
* @see IOCase#SYSTEM
*/
public static boolean wildcardMatchOnSystem(final String fileName, final String wildcardMatcher) {
diff --git a/src/main/java/org/apache/commons/io/HexDump.java b/src/main/java/org/apache/commons/io/HexDump.java
index cb7efa7b2f2..8b4d56b9ac7 100644
--- a/src/main/java/org/apache/commons/io/HexDump.java
+++ b/src/main/java/org/apache/commons/io/HexDump.java
@@ -62,11 +62,11 @@ public class HexDump {
* characters (if any) that those bytes represent printed per each line
* of output.
*
- * @param data the byte array to be dumped
- * @param appendable the Appendable to which the data is to be written
+ * @param data The byte array to be dumped.
+ * @param appendable The Appendable to which the data is to be written.
* @throws IOException is thrown if anything goes wrong writing
- * the data to appendable
- * @throws NullPointerException if the output appendable is null
+ * the data to appendable.
+ * @throws NullPointerException if the output appendable is null.
* @since 2.12.0
*/
public static void dump(final byte[] data, final Appendable appendable)
@@ -89,16 +89,16 @@ public static void dump(final byte[] data, final Appendable appendable)
* the first byte on that line is located.
*
*
- * @param data the byte array to be dumped
- * @param offset offset of the byte array within a larger entity
- * @param appendable the Appendable to which the data is to be written
- * @param index initial index into the byte array
- * @param length number of bytes to dump from the array
+ * @param data The byte array to be dumped.
+ * @param offset offset of the byte array within a larger entity.
+ * @param appendable The Appendable to which the data is to be written.
+ * @param index initial index into the byte array.
+ * @param length number of bytes to dump from the array.
* @throws IOException is thrown if anything goes wrong writing
- * the data to appendable
+ * the data to appendable.
* @throws ArrayIndexOutOfBoundsException if the index or length is
- * outside the data array's bounds
- * @throws NullPointerException if the output appendable is null
+ * outside the data array's bounds.
+ * @throws NullPointerException if the output appendable is null.
* @since 2.12.0
*/
public static void dump(final byte[] data, final long offset,
@@ -169,19 +169,19 @@ public static void dump(final byte[] data, final long offset,
* data array are dumped.
*
*
- * This method uses the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * This method uses the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
*
- * @param data the byte array to be dumped
- * @param offset offset of the byte array within a larger entity
- * @param stream the OutputStream to which the data is to be
- * written
- * @param index initial index into the byte array
+ * @param data The byte array to be dumped.
+ * @param offset offset of the byte array within a larger entity.
+ * @param stream The OutputStream to which the data is to be
+ * written.
+ * @param index initial index into the byte array.
* @throws IOException is thrown if anything goes wrong writing
- * the data to stream
+ * the data to stream.
* @throws ArrayIndexOutOfBoundsException if the index is
- * outside the data array's bounds
- * @throws NullPointerException if the output stream is null
+ * outside the data array's bounds.
+ * @throws NullPointerException if the output stream is null.
*/
@SuppressWarnings("resource") // Caller closes stream
public static void dump(final byte[] data, final long offset,
@@ -197,8 +197,8 @@ public static void dump(final byte[] data, final long offset,
/**
* Dumps a byte value into a StringBuilder.
*
- * @param builder the StringBuilder to dump the value in
- * @param value the byte value to be dumped
+ * @param builder The StringBuilder to dump the value in.
+ * @param value The byte value to be dumped.
* @return StringBuilder containing the dumped value.
*/
private static StringBuilder dump(final StringBuilder builder, final byte value) {
@@ -211,8 +211,8 @@ private static StringBuilder dump(final StringBuilder builder, final byte value)
/**
* Dumps a long value into a StringBuilder.
*
- * @param builder the StringBuilder to dump the value in
- * @param value the long value to be dumped
+ * @param builder The StringBuilder to dump the value in.
+ * @param value The long value to be dumped.
* @return StringBuilder containing the dumped value.
*/
private static StringBuilder dump(final StringBuilder builder, final long value) {
diff --git a/src/main/java/org/apache/commons/io/IOCase.java b/src/main/java/org/apache/commons/io/IOCase.java
index 7fee424f489..501d2382178 100644
--- a/src/main/java/org/apache/commons/io/IOCase.java
+++ b/src/main/java/org/apache/commons/io/IOCase.java
@@ -21,7 +21,7 @@
import java.util.stream.Stream;
/**
- * Enumeration of IO case sensitivity.
+ * Enumerates IO case sensitivity types.
*
* Different filing systems have different rules for case-sensitivity.
* Windows is case-insensitive, Unix is case-sensitive.
@@ -72,9 +72,9 @@ public enum IOCase {
/**
* Looks up an IOCase by name.
*
- * @param name the name to find
- * @return the IOCase object
- * @throws IllegalArgumentException if the name is invalid
+ * @param name The name to find.
+ * @return The IOCase object.
+ * @throws IllegalArgumentException if the name is invalid.
*/
public static IOCase forName(final String name) {
return Stream.of(values()).filter(ioCase -> ioCase.getName().equals(name)).findFirst()
@@ -84,7 +84,7 @@ public static IOCase forName(final String name) {
/**
* Tests for cases sensitivity in a null-safe manner.
*
- * @param ioCase an IOCase.
+ * @param ioCase An IOCase.
* @return true if the input is non-null and {@link #isCaseSensitive()}.
* @since 2.10.0
*/
@@ -95,9 +95,9 @@ public static boolean isCaseSensitive(final IOCase ioCase) {
/**
* Returns the given value if not-null, the defaultValue if null.
*
- * @param value the value to test.
- * @param defaultValue the default value.
- * @return the given value if not-null, the defaultValue if null.
+ * @param value The value to test, may be null.
+ * @param defaultValue The default value.
+ * @return The given value if not-null, the defaultValue if null.
* @since 2.12.0
*/
public static IOCase value(final IOCase value, final IOCase defaultValue) {
@@ -113,8 +113,8 @@ public static IOCase value(final IOCase value, final IOCase defaultValue) {
/**
* Constructs a new instance.
*
- * @param name the name.
- * @param sensitive the sensitivity.
+ * @param name The name.
+ * @param sensitive The sensitivity.
*/
IOCase(final String name, final boolean sensitive) {
this.name = name;
@@ -128,8 +128,8 @@ public static IOCase value(final IOCase value, final IOCase defaultValue) {
* into account.
*
*
- * @param str1 the first string to compare, not null.
- * @param str2 the second string to compare, not null.
+ * @param str1 The first string to compare, not null.
+ * @param str2 The second string to compare, not null.
* @return true if equal using the case rules.
* @throws NullPointerException if either string is null.
*/
@@ -146,8 +146,8 @@ public int checkCompareTo(final String str1, final String str2) {
* into account.
*
*
- * @param str the string to check.
- * @param end the end to compare against.
+ * @param str The string to check.
+ * @param end The end to compare against.
* @return true if equal using the case rules, false if either input is null.
*/
public boolean checkEndsWith(final String str, final String end) {
@@ -165,8 +165,8 @@ public boolean checkEndsWith(final String str, final String end) {
* into account.
*
*
- * @param str1 the first string to compare.
- * @param str2 the second string to compare.
+ * @param str1 The first string to compare.
+ * @param str2 The second string to compare.
* @return true if equal using the case rules.
*/
public boolean checkEquals(final String str1, final String str2) {
@@ -181,10 +181,10 @@ public boolean checkEquals(final String str1, final String str2) {
* but takes case-sensitivity into account.
*
*
- * @param str the string to check.
- * @param strStartIndex the index to start at in str.
- * @param search the start to search for.
- * @return the first index of the search String,
+ * @param str The string to check.
+ * @param strStartIndex The index to start at in str.
+ * @param search The start to search for.
+ * @return The first index of the search String,
* -1 if no match or {@code null} string input.
* @since 2.0
*/
@@ -209,9 +209,9 @@ public int checkIndexOf(final String str, final int strStartIndex, final String
* but takes case-sensitivity into account.
*
*
- * @param str the string to check.
- * @param strStartIndex the index to start at in str.
- * @param search the start to search for,.
+ * @param str The string to check.
+ * @param strStartIndex The index to start at in str.
+ * @param search The start to search for,.
* @return true if equal using the case rules.
*/
public boolean checkRegionMatches(final String str, final int strStartIndex, final String search) {
@@ -225,8 +225,8 @@ public boolean checkRegionMatches(final String str, final int strStartIndex, fin
* into account.
*
*
- * @param str the string to check.
- * @param start the start to compare against.
+ * @param str The string to check.
+ * @param start The start to compare against.
* @return true if equal using the case rules, false if either input is null.
*/
public boolean checkStartsWith(final String str, final String start) {
@@ -236,7 +236,7 @@ public boolean checkStartsWith(final String str, final String start) {
/**
* Gets the name of the constant.
*
- * @return the name of the constant
+ * @return The name of the constant.
*/
public String getName() {
return name;
@@ -255,7 +255,7 @@ public boolean isCaseSensitive() {
* Replaces the enumeration from the stream with a real one.
* This ensures that the correct flag is set for SYSTEM.
*
- * @return the resolved object.
+ * @return The resolved object.
*/
private Object readResolve() {
return forName(name);
@@ -264,7 +264,7 @@ private Object readResolve() {
/**
* Gets a string describing the sensitivity.
*
- * @return a string describing the sensitivity.
+ * @return A string describing the sensitivity.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/IOExceptionList.java b/src/main/java/org/apache/commons/io/IOExceptionList.java
index 740bedb6789..63f34218432 100644
--- a/src/main/java/org/apache/commons/io/IOExceptionList.java
+++ b/src/main/java/org/apache/commons/io/IOExceptionList.java
@@ -71,7 +71,7 @@ private static String toMessage(final List extends Throwable> causeList) {
/**
* Constructs a new exception caused by a list of exceptions.
*
- * @param causeList a list of cause exceptions.
+ * @param causeList A list of cause exceptions.
*/
public IOExceptionList(final List extends Throwable> causeList) {
this(toMessage(causeList), causeList);
@@ -81,7 +81,7 @@ public IOExceptionList(final List extends Throwable> causeList) {
* Constructs a new exception caused by a list of exceptions.
*
* @param message The detail message, see {@link #getMessage()}.
- * @param causeList a list of cause exceptions.
+ * @param causeList A list of cause exceptions.
* @since 2.9.0
*/
public IOExceptionList(final String message, final List extends Throwable> causeList) {
@@ -126,7 +126,7 @@ public List getCauseList() {
* Works around Throwable and Generics, may fail at runtime depending on the argument value.
*
* @param type of exception to return.
- * @param clazz the target type
+ * @param clazz The target type.
* @return The list of causes.
*/
public List getCauseList(final Class clazz) {
diff --git a/src/main/java/org/apache/commons/io/IOExceptionWithCause.java b/src/main/java/org/apache/commons/io/IOExceptionWithCause.java
index af25e8b0a40..b5dbba671bb 100644
--- a/src/main/java/org/apache/commons/io/IOExceptionWithCause.java
+++ b/src/main/java/org/apache/commons/io/IOExceptionWithCause.java
@@ -20,10 +20,10 @@
import java.io.IOException;
/**
- * Subclasses IOException with the {@link Throwable} constructors missing before Java 6.
+ * Subclasses {@link IOException} with the {@link Throwable} constructors missing before Java 6.
*
* @since 1.4
- * @deprecated (since 2.5) use {@link IOException} instead
+ * @deprecated (since 2.5) use {@link IOException} instead.
*/
@Deprecated
public class IOExceptionWithCause extends IOException {
@@ -41,7 +41,7 @@ public class IOExceptionWithCause extends IOException {
*
*
* @param message
- * the message (see {@link #getMessage()})
+ * the message (see {@link #getMessage()}).
* @param cause
* the cause (see {@link #getCause()}). A {@code null} value is allowed.
*/
diff --git a/src/main/java/org/apache/commons/io/IOIndexedException.java b/src/main/java/org/apache/commons/io/IOIndexedException.java
index fcb84334ff6..958d8307317 100644
--- a/src/main/java/org/apache/commons/io/IOIndexedException.java
+++ b/src/main/java/org/apache/commons/io/IOIndexedException.java
@@ -27,6 +27,7 @@
public class IOIndexedException extends IOException {
private static final long serialVersionUID = 1L;
+
/**
* Converts input to a suitable String for exception message.
*
diff --git a/src/main/java/org/apache/commons/io/IORandomAccessFile.java b/src/main/java/org/apache/commons/io/IORandomAccessFile.java
index 9b4aea52dec..7fd23b42201 100644
--- a/src/main/java/org/apache/commons/io/IORandomAccessFile.java
+++ b/src/main/java/org/apache/commons/io/IORandomAccessFile.java
@@ -19,6 +19,7 @@
import java.io.File;
import java.io.FileNotFoundException;
+import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Objects;
@@ -37,8 +38,8 @@ public final class IORandomAccessFile extends RandomAccessFile {
/**
* Constructs a new instance by calling {@link RandomAccessFile#RandomAccessFile(File, String)}.
*
- * @param file the file object
- * @param mode the access mode, as described in {@link RandomAccessFile#RandomAccessFile(File, String)}.
+ * @param file The file object.
+ * @param mode The access mode, as described in {@link RandomAccessFile#RandomAccessFile(File, String)}.
* @throws FileNotFoundException Thrown by {@link RandomAccessFile#RandomAccessFile(File, String)}.
* @see RandomAccessFile#RandomAccessFile(File, String)
*/
@@ -51,8 +52,8 @@ public IORandomAccessFile(final File file, final String mode) throws FileNotFoun
/**
* Constructs a new instance by calling {@link RandomAccessFile#RandomAccessFile(String, String)}.
*
- * @param name the file object
- * @param mode the access mode, as described in {@link RandomAccessFile#RandomAccessFile(String, String)}.
+ * @param name The system-dependent file name.
+ * @param mode The access mode, as described in {@link RandomAccessFile#RandomAccessFile(String, String)}.
* @throws FileNotFoundException Thrown by {@link RandomAccessFile#RandomAccessFile(String, String)}.
* @see RandomAccessFile#RandomAccessFile(String, String)
*/
@@ -62,10 +63,30 @@ public IORandomAccessFile(final String name, final String mode) throws FileNotFo
this.mode = mode;
}
+ /**
+ * Clears the contents of this existing file by filling it with NUL ({@code 0)} bytes.
+ *
+ * @return {@code this} instance.
+ * @throws FileNotFoundException See {@link #IORandomAccessFile(File, String)}.
+ * @throws IOException Thrown if an I/O error occurs.
+ */
+ public IORandomAccessFile clear() throws IOException {
+ final long length = length();
+ final byte[] zeroBuffer = IOUtils.byteArray();
+ long bytesWritten = 0;
+ while (bytesWritten < length) {
+ final long remaining = length - bytesWritten;
+ final int toWrite = (int) Math.min(zeroBuffer.length, remaining);
+ write(zeroBuffer, 0, toWrite);
+ bytesWritten += toWrite;
+ }
+ return this;
+ }
+
/**
* Gets the file passed to {@link #IORandomAccessFile(File, String)}.
*
- * @return the file passed to {@link #IORandomAccessFile(File, String)}.
+ * @return The file passed to {@link #IORandomAccessFile(File, String)}.
*/
public File getFile() {
return file;
@@ -74,14 +95,14 @@ public File getFile() {
/**
* Gets the mode passed to {@link #IORandomAccessFile(File, String)}.
*
- * @return the mode passed to {@link #IORandomAccessFile(File, String)}.
+ * @return The mode passed to {@link #IORandomAccessFile(File, String)}.
*/
public String getMode() {
return mode;
}
/**
- * Returns the pathname string of this abstract pathname. This is just the string returned by the {@link File#toString()} method.
+ * Returns the path name string of this abstract pathname. This is just the string returned by the {@link File#toString()} method.
*
* @return The string form of the File's abstract pathname.
* @see File#toString()
@@ -90,5 +111,4 @@ public String getMode() {
public String toString() {
return Objects.toString(file);
}
-
}
diff --git a/src/main/java/org/apache/commons/io/IOUtils.java b/src/main/java/org/apache/commons/io/IOUtils.java
index a882d4d87cb..b29489776b2 100644
--- a/src/main/java/org/apache/commons/io/IOUtils.java
+++ b/src/main/java/org/apache/commons/io/IOUtils.java
@@ -81,25 +81,20 @@
* This class provides static utility methods for input/output operations.
*
*
- *
closeQuietly - these methods close a stream ignoring nulls and exceptions
- *
toXxx/read - these methods read data from a stream
- *
write - these methods write data to a stream
- *
copy - these methods copy all the data from one stream to another
- *
contentEquals - these methods compare the content of two streams
+ *
closeQuietly - these methods close a stream ignoring nulls and exceptions
+ *
toXxx/read - these methods read data from a stream
+ *
write - these methods write data to a stream
+ *
copy - these methods copy all the data from one stream to another
+ *
contentEquals - these methods compare the content of two streams
*
*
- * The byte-to-char methods and char-to-byte methods involve a conversion step.
- * Two methods are provided in each case, one that uses the platform default
- * encoding and the other which allows you to specify an encoding. You are
- * encouraged to always specify an encoding because relying on the platform
- * default can lead to unexpected results, for example when moving from
- * development to production.
+ * The byte-to-char methods and char-to-byte methods involve a conversion step. Two methods are provided in each case, one that uses the platform default
+ * encoding and the other which allows you to specify an encoding. You are encouraged to always specify an encoding because relying on the platform default can
+ * lead to unexpected results, for example when moving from development to production.
*
*
- * All the methods in this class that read a stream are buffered internally.
- * This means that there is no cause to use a {@link BufferedInputStream}
- * or {@link BufferedReader}. The default buffer size of 4K has been shown
- * to be efficient in tests.
+ * All the methods in this class that read a stream are buffered internally. This means that there is no cause to use a {@link BufferedInputStream} or
+ * {@link BufferedReader}. The default buffer size of 4K has been shown to be efficient in tests.
*
*
* The various copy methods all delegate the actual copying to one of the following methods:
@@ -110,18 +105,14 @@
*
*
- * For example, {@link #copy(InputStream, OutputStream)} calls {@link #copyLarge(InputStream, OutputStream)}
- * which calls {@link #copy(InputStream, OutputStream, int)} which creates the buffer and calls
- * {@link #copyLarge(InputStream, OutputStream, byte[])}.
+ * For example, {@link #copy(InputStream, OutputStream)} calls {@link #copyLarge(InputStream, OutputStream)} which calls
+ * {@link #copy(InputStream, OutputStream, int)} which creates the buffer and calls {@link #copyLarge(InputStream, OutputStream, byte[])}.
*
- * Applications can re-use buffers by using the underlying methods directly.
- * This may improve performance for applications that need to do a lot of copying.
+ * Applications can re-use buffers by using the underlying methods directly. This may improve performance for applications that need to do a lot of copying.
*
*
- * Wherever possible, the methods in this class do not flush or close
- * the stream. This is to avoid making non-portable assumptions about the
- * streams' origin and further use. Thus the caller is still responsible for
- * closing streams after use.
+ * Wherever possible, the methods in this class do not flush or close the stream. This is to avoid making non-portable assumptions about the streams'
+ * origin and further use. Thus the caller is still responsible for closing streams after use.
*
*
* Provenance: Excalibur.
@@ -132,6 +123,142 @@ public class IOUtils {
// Writer. Each method should take at least one of these as a parameter,
// or return one of them.
+ /**
+ * Holder for per-thread internal scratch buffer.
+ *
+ * Buffers are created lazily and reused within the same thread to reduce allocation overhead. In the rare case of reentrant access, a temporary buffer is
+ * allocated to avoid data corruption.
+ *
+ */
+ static final class ScratchBytes implements AutoCloseable {
+
+ /**
+ * Wraps an internal byte array. [0] boolean in use. [1] byte[] buffer.
+ */
+ private static final ThreadLocal LOCAL = ThreadLocal.withInitial(() -> new Object[] { false, byteArray() });
+
+ private static final ScratchBytes INSTANCE = new ScratchBytes(null);
+
+ /**
+ * Gets the internal byte array buffer.
+ *
+ * @return The internal byte array buffer.
+ */
+ static ScratchBytes get() {
+ final Object[] holder = LOCAL.get();
+ // If already in use, return a new array
+ if ((boolean) holder[0]) {
+ return new ScratchBytes(byteArray());
+ }
+ holder[0] = true;
+ return INSTANCE;
+ }
+
+ /**
+ * The buffer, or null if using the thread-local buffer.
+ */
+ private final byte[] buffer;
+
+ private ScratchBytes(final byte[] buffer) {
+ this.buffer = buffer;
+ }
+
+ byte[] array() {
+ return buffer != null ? buffer : (byte[]) LOCAL.get()[1];
+ }
+
+ /**
+ * If the buffer is the internal array, clear and release it for reuse.
+ */
+ @Override
+ public void close() {
+ if (buffer == null) {
+ final Object[] holder = LOCAL.get();
+ Arrays.fill((byte[]) holder[1], (byte) 0);
+ holder[0] = false;
+ }
+ }
+ }
+
+ /**
+ * Holder for per-thread internal scratch buffer.
+ *
+ * Buffers are created lazily and reused within the same thread to reduce allocation overhead. In the rare case of reentrant access, a temporary buffer is
+ * allocated to avoid data corruption.
+ *
+ */
+ static final class ScratchChars implements AutoCloseable {
+
+ /**
+ * Wraps an internal char array. [0] boolean in use. [1] char[] buffer.
+ */
+ private static final ThreadLocal LOCAL = ThreadLocal.withInitial(() -> new Object[] { false, charArray() });
+
+ private static final ScratchChars INSTANCE = new ScratchChars(null);
+
+ /**
+ * Gets the internal char array buffer.
+ *
+ * @return The internal char array buffer.
+ */
+ static ScratchChars get() {
+ final Object[] holder = LOCAL.get();
+ // If already in use, return a new array
+ if ((boolean) holder[0]) {
+ return new ScratchChars(charArray());
+ }
+ holder[0] = true;
+ return INSTANCE;
+ }
+
+ /**
+ * The buffer, or null if using the thread-local buffer.
+ */
+ private final char[] buffer;
+
+ private ScratchChars(final char[] buffer) {
+ this.buffer = buffer;
+ }
+
+ char[] array() {
+ return buffer != null ? buffer : (char[]) LOCAL.get()[1];
+ }
+
+ /**
+ * If the buffer is the internal array, clear and release it for reuse.
+ */
+ @Override
+ public void close() {
+ if (buffer == null) {
+ final Object[] holder = LOCAL.get();
+ Arrays.fill((char[]) holder[1], (char) 0);
+ holder[0] = false;
+ }
+ }
+ }
+
/**
* CR char '{@value}'.
*
@@ -162,12 +289,13 @@ public class IOUtils {
/**
* A singleton empty byte array.
*
- * @since 2.9.0
+ * @since 2.9.0
*/
public static final byte[] EMPTY_BYTE_ARRAY = {};
/**
* Represents the end-of-file (or stream) value {@value}.
+ *
* @since 2.5 (made public)
*/
public static final int EOF = -1;
@@ -201,26 +329,6 @@ public class IOUtils {
*/
public static final String LINE_SEPARATOR_WINDOWS = StandardLineSeparator.CRLF.getString();
- /**
- * Internal byte array buffer, intended for both reading and writing.
- */
- private static final ThreadLocal SCRATCH_BYTE_BUFFER_RW = ThreadLocal.withInitial(IOUtils::byteArray);
-
- /**
- * Internal byte array buffer, intended for write only operations.
- */
- private static final byte[] SCRATCH_BYTE_BUFFER_WO = byteArray();
-
- /**
- * Internal char array buffer, intended for both reading and writing.
- */
- private static final ThreadLocal SCRATCH_CHAR_BUFFER_RW = ThreadLocal.withInitial(IOUtils::charArray);
-
- /**
- * Internal char array buffer, intended for write only operations.
- */
- private static final char[] SCRATCH_CHAR_BUFFER_WO = charArray();
-
/**
* The maximum size of an array in many Java VMs.
*
@@ -232,11 +340,10 @@ public class IOUtils {
public static final int SOFT_MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8;
/**
- * Returns the given InputStream if it is already a {@link BufferedInputStream}, otherwise creates a
- * BufferedInputStream from the given InputStream.
+ * Returns the given InputStream if it is already a {@link BufferedInputStream}, otherwise creates a BufferedInputStream from the given InputStream.
*
- * @param inputStream the InputStream to wrap or return (not null).
- * @return the given InputStream or a new {@link BufferedInputStream} for the given InputStream.
+ * @param inputStream The InputStream to wrap or return (not null).
+ * @return The given InputStream or a new {@link BufferedInputStream} for the given InputStream.
* @throws NullPointerException if the input parameter is null.
* @since 2.5
*/
@@ -245,17 +352,15 @@ public static BufferedInputStream buffer(final InputStream inputStream) {
// reject null early on rather than waiting for IO operation to fail
// not checked by BufferedInputStream
Objects.requireNonNull(inputStream, "inputStream");
- return inputStream instanceof BufferedInputStream ?
- (BufferedInputStream) inputStream : new BufferedInputStream(inputStream);
+ return inputStream instanceof BufferedInputStream ? (BufferedInputStream) inputStream : new BufferedInputStream(inputStream);
}
/**
- * Returns the given InputStream if it is already a {@link BufferedInputStream}, otherwise creates a
- * BufferedInputStream from the given InputStream.
+ * Returns the given InputStream if it is already a {@link BufferedInputStream}, otherwise creates a BufferedInputStream from the given InputStream.
*
- * @param inputStream the InputStream to wrap or return (not null).
- * @param size the buffer size, if a new BufferedInputStream is created.
- * @return the given InputStream or a new {@link BufferedInputStream} for the given InputStream.
+ * @param inputStream The InputStream to wrap or return (not null).
+ * @param size The buffer size, if a new BufferedInputStream is created.
+ * @return The given InputStream or a new {@link BufferedInputStream} for the given InputStream.
* @throws NullPointerException if the input parameter is null.
* @since 2.5
*/
@@ -264,16 +369,14 @@ public static BufferedInputStream buffer(final InputStream inputStream, final in
// reject null early on rather than waiting for IO operation to fail
// not checked by BufferedInputStream
Objects.requireNonNull(inputStream, "inputStream");
- return inputStream instanceof BufferedInputStream ?
- (BufferedInputStream) inputStream : new BufferedInputStream(inputStream, size);
+ return inputStream instanceof BufferedInputStream ? (BufferedInputStream) inputStream : new BufferedInputStream(inputStream, size);
}
/**
- * Returns the given OutputStream if it is already a {@link BufferedOutputStream}, otherwise creates a
- * BufferedOutputStream from the given OutputStream.
+ * Returns the given OutputStream if it is already a {@link BufferedOutputStream}, otherwise creates a BufferedOutputStream from the given OutputStream.
*
- * @param outputStream the OutputStream to wrap or return (not null).
- * @return the given OutputStream or a new {@link BufferedOutputStream} for the given OutputStream
+ * @param outputStream The OutputStream to wrap or return (not null).
+ * @return The given OutputStream or a new {@link BufferedOutputStream} for the given OutputStream.
* @throws NullPointerException if the input parameter is null.
* @since 2.5
*/
@@ -282,17 +385,15 @@ public static BufferedOutputStream buffer(final OutputStream outputStream) {
// reject null early on rather than waiting for IO operation to fail
// not checked by BufferedInputStream
Objects.requireNonNull(outputStream, "outputStream");
- return outputStream instanceof BufferedOutputStream ?
- (BufferedOutputStream) outputStream : new BufferedOutputStream(outputStream);
+ return outputStream instanceof BufferedOutputStream ? (BufferedOutputStream) outputStream : new BufferedOutputStream(outputStream);
}
/**
- * Returns the given OutputStream if it is already a {@link BufferedOutputStream}, otherwise creates a
- * BufferedOutputStream from the given OutputStream.
+ * Returns the given OutputStream if it is already a {@link BufferedOutputStream}, otherwise creates a BufferedOutputStream from the given OutputStream.
*
- * @param outputStream the OutputStream to wrap or return (not null).
- * @param size the buffer size, if a new BufferedOutputStream is created.
- * @return the given OutputStream or a new {@link BufferedOutputStream} for the given OutputStream.
+ * @param outputStream The OutputStream to wrap or return (not null).
+ * @param size The buffer size, if a new BufferedOutputStream is created.
+ * @return The given OutputStream or a new {@link BufferedOutputStream} for the given OutputStream.
* @throws NullPointerException if the input parameter is null.
* @since 2.5
*/
@@ -301,16 +402,14 @@ public static BufferedOutputStream buffer(final OutputStream outputStream, final
// reject null early on rather than waiting for IO operation to fail
// not checked by BufferedInputStream
Objects.requireNonNull(outputStream, "outputStream");
- return outputStream instanceof BufferedOutputStream ?
- (BufferedOutputStream) outputStream : new BufferedOutputStream(outputStream, size);
+ return outputStream instanceof BufferedOutputStream ? (BufferedOutputStream) outputStream : new BufferedOutputStream(outputStream, size);
}
/**
- * Returns the given reader if it is already a {@link BufferedReader}, otherwise creates a BufferedReader from
- * the given reader.
+ * Returns the given reader if it is already a {@link BufferedReader}, otherwise creates a BufferedReader from the given reader.
*
- * @param reader the reader to wrap or return (not null).
- * @return the given reader or a new {@link BufferedReader} for the given reader.
+ * @param reader The reader to wrap or return (not null).
+ * @return The given reader or a new {@link BufferedReader} for the given reader.
* @throws NullPointerException if the input parameter is null.
* @since 2.5
*/
@@ -319,12 +418,11 @@ public static BufferedReader buffer(final Reader reader) {
}
/**
- * Returns the given reader if it is already a {@link BufferedReader}, otherwise creates a BufferedReader from the
- * given reader.
+ * Returns the given reader if it is already a {@link BufferedReader}, otherwise creates a BufferedReader from the given reader.
*
- * @param reader the reader to wrap or return (not null).
- * @param size the buffer size, if a new BufferedReader is created.
- * @return the given reader or a new {@link BufferedReader} for the given reader.
+ * @param reader The reader to wrap or return (not null).
+ * @param size The buffer size, if a new BufferedReader is created.
+ * @return The given reader or a new {@link BufferedReader} for the given reader.
* @throws NullPointerException if the input parameter is null.
* @since 2.5
*/
@@ -333,11 +431,10 @@ public static BufferedReader buffer(final Reader reader, final int size) {
}
/**
- * Returns the given Writer if it is already a {@link BufferedWriter}, otherwise creates a BufferedWriter from the
- * given Writer.
+ * Returns the given Writer if it is already a {@link BufferedWriter}, otherwise creates a BufferedWriter from the given Writer.
*
- * @param writer the Writer to wrap or return (not null).
- * @return the given Writer or a new {@link BufferedWriter} for the given Writer.
+ * @param writer The Writer to wrap or return (not null).
+ * @return The given Writer or a new {@link BufferedWriter} for the given Writer.
* @throws NullPointerException if the input parameter is null.
* @since 2.5
*/
@@ -346,12 +443,11 @@ public static BufferedWriter buffer(final Writer writer) {
}
/**
- * Returns the given Writer if it is already a {@link BufferedWriter}, otherwise creates a BufferedWriter from the
- * given Writer.
+ * Returns the given Writer if it is already a {@link BufferedWriter}, otherwise creates a BufferedWriter from the given Writer.
*
- * @param writer the Writer to wrap or return (not null).
- * @param size the buffer size, if a new BufferedWriter is created.
- * @return the given Writer or a new {@link BufferedWriter} for the given Writer.
+ * @param writer The Writer to wrap or return (not null).
+ * @param size The buffer size, if a new BufferedWriter is created.
+ * @return The given Writer or a new {@link BufferedWriter} for the given Writer.
* @throws NullPointerException if the input parameter is null.
* @since 2.5
*/
@@ -362,7 +458,7 @@ public static BufferedWriter buffer(final Writer writer, final int size) {
/**
* Returns a new byte array of size {@link #DEFAULT_BUFFER_SIZE}.
*
- * @return a new byte array of size {@link #DEFAULT_BUFFER_SIZE}.
+ * @return A new byte array of size {@link #DEFAULT_BUFFER_SIZE}.
* @since 2.9.0
*/
public static byte[] byteArray() {
@@ -370,12 +466,10 @@ public static byte[] byteArray() {
}
/**
- * Returns a new byte array of the given size.
- *
- * TODO Consider guarding or warning against large allocations.
+ * Returns a new byte array of the given size. TODO Consider guarding or warning against large allocations.
*
* @param size array size.
- * @return a new byte array of the given size.
+ * @return A new byte array of the given size.
* @throws NegativeArraySizeException if the size is negative.
* @since 2.9.0
*/
@@ -386,7 +480,7 @@ public static byte[] byteArray(final int size) {
/**
* Returns a new char array of size {@link #DEFAULT_BUFFER_SIZE}.
*
- * @return a new char array of size {@link #DEFAULT_BUFFER_SIZE}.
+ * @return A new char array of size {@link #DEFAULT_BUFFER_SIZE}.
* @since 2.9.0
*/
private static char[] charArray() {
@@ -394,12 +488,10 @@ private static char[] charArray() {
}
/**
- * Returns a new char array of the given size.
- *
- * TODO Consider guarding or warning against large allocations.
+ * Returns a new char array of the given size. TODO Consider guarding or warning against large allocations.
*
* @param size array size.
- * @return a new char array of the given size.
+ * @return A new char array of the given size.
* @since 2.9.0
*/
private static char[] charArray(final int size) {
@@ -408,19 +500,23 @@ private static char[] charArray(final int size) {
/**
* Validates that the sub-range {@code [off, off + len)} is within the bounds of the given array.
- *
- *
The range is valid if all of the following hold:
+ *
+ * The range is valid if all of the following hold:
+ *
*
- *
{@code off >= 0}
- *
{@code len >= 0}
- *
{@code off + len <= array.length}
+ *
{@code off >= 0}
+ *
{@code len >= 0}
+ *
{@code off + len <= array.length}
*
+ *
+ * If the range is invalid, throws {@link IndexOutOfBoundsException} with a descriptive message.
+ *
+ *
+ * Typical usage in {@link InputStream#read(byte[], int, int)} and {@link OutputStream#write(byte[], int, int)} implementations:
+ *
*
- *
If the range is invalid, throws {@link IndexOutOfBoundsException} with a descriptive message.
- *
- *
Typical usage in {@link InputStream#read(byte[], int, int)} and {@link OutputStream#write(byte[], int, int)} implementations:
- *
- *
+ *
+ *
* public int read(byte[] b, int off, int len) throws IOException {
* IOUtils.checkFromIndexSize(b, off, len);
* if (len == 0) {
@@ -438,13 +534,14 @@ private static char[] charArray(final int size) {
* ensureOpen();
* // perform write...
* }
- *
+ *
+ *
*
- * @param array the array against which the range is validated
- * @param off the starting offset into the array (inclusive)
- * @param len the number of elements to access
- * @throws NullPointerException if {@code array} is {@code null}
- * @throws IndexOutOfBoundsException if the range {@code [off, off + len)} is out of bounds for {@code array}
+ * @param array The array against which the range is validated.
+ * @param off The starting offset into the array (inclusive).
+ * @param len The number of elements to access.
+ * @throws NullPointerException if {@code array} is {@code null}.
+ * @throws IndexOutOfBoundsException if the range {@code [off, off + len)} is out of bounds for {@code array}.
* @see InputStream#read(byte[], int, int)
* @see OutputStream#write(byte[], int, int)
* @since 2.21.0
@@ -455,19 +552,23 @@ public static void checkFromIndexSize(final byte[] array, final int off, final i
/**
* Validates that the sub-range {@code [off, off + len)} is within the bounds of the given array.
- *
- *
The range is valid if all of the following hold:
+ *
+ * The range is valid if all of the following hold:
+ *
*
- *
{@code off >= 0}
- *
{@code len >= 0}
- *
{@code off + len <= array.length}
+ *
{@code off >= 0}
+ *
{@code len >= 0}
+ *
{@code off + len <= array.length}
*
+ *
+ * If the range is invalid, throws {@link IndexOutOfBoundsException} with a descriptive message.
+ *
+ *
+ * Typical usage in {@link Reader#read(char[], int, int)} and {@link Writer#write(char[], int, int)} implementations:
+ *
*
- *
If the range is invalid, throws {@link IndexOutOfBoundsException} with a descriptive message.
- *
- *
Typical usage in {@link Reader#read(char[], int, int)} and {@link Writer#write(char[], int, int)} implementations:
- *
- *
+ *
+ *
* public int read(char[] cbuf, int off, int len) throws IOException {
* ensureOpen();
* IOUtils.checkFromIndexSize(cbuf, off, len);
@@ -485,13 +586,14 @@ public static void checkFromIndexSize(final byte[] array, final int off, final i
* }
* // perform write...
* }
- *
+ *
+ *
*
- * @param array the array against which the range is validated
- * @param off the starting offset into the array (inclusive)
- * @param len the number of characters to access
- * @throws NullPointerException if {@code array} is {@code null}
- * @throws IndexOutOfBoundsException if the range {@code [off, off + len)} is out of bounds for {@code array}
+ * @param array The array against which the range is validated.
+ * @param off The starting offset into the array (inclusive).
+ * @param len The number of characters to access.
+ * @throws NullPointerException if {@code array} is {@code null}.
+ * @throws IndexOutOfBoundsException if the range {@code [off, off + len)} is out of bounds for {@code array}.
* @see Reader#read(char[], int, int)
* @see Writer#write(char[], int, int)
* @since 2.21.0
@@ -500,21 +602,31 @@ public static void checkFromIndexSize(final char[] array, final int off, final i
checkFromIndexSize(off, len, Objects.requireNonNull(array, "char array").length);
}
+ static void checkFromIndexSize(final int off, final int len, final int arrayLength) {
+ if ((off | len | arrayLength) < 0 || arrayLength - len < off) {
+ throw new IndexOutOfBoundsException(String.format("Range [%s, %The range is valid if all of the following hold:
+ *
+ * The range is valid if all of the following hold:
+ *
*
- *
{@code off >= 0}
- *
{@code len >= 0}
- *
{@code off + len <= str.length()}
+ *
{@code off >= 0}
+ *
{@code len >= 0}
+ *
{@code off + len <= str.length()}
*
+ *
+ * If the range is invalid, throws {@link IndexOutOfBoundsException} with a descriptive message.
+ *
If the range is invalid, throws {@link IndexOutOfBoundsException} with a descriptive message.
- *
- *
Typical usage in {@link Writer#write(String, int, int)} implementations:
- *
- *
+ *
+ *
* public void write(String str, int off, int len) throws IOException {
* IOUtils.checkFromIndexSize(str, off, len);
* if (len == 0) {
@@ -522,13 +634,14 @@ public static void checkFromIndexSize(final char[] array, final int off, final i
* }
* // perform write...
* }
- *
+ *
+ *
*
- * @param str the string against which the range is validated
- * @param off the starting offset into the string (inclusive)
- * @param len the number of characters to write
- * @throws NullPointerException if {@code str} is {@code null}
- * @throws IndexOutOfBoundsException if the range {@code [off, off + len)} is out of bounds for {@code str}
+ * @param str The string against which the range is validated.
+ * @param off The starting offset into the string (inclusive).
+ * @param len The number of characters to write.
+ * @throws NullPointerException if {@code str} is {@code null}.
+ * @throws IndexOutOfBoundsException if the range {@code [off, off + len)} is out of bounds for {@code str}.
* @see Writer#write(String, int, int)
* @since 2.21.0
*/
@@ -536,40 +649,40 @@ public static void checkFromIndexSize(final String str, final int off, final int
checkFromIndexSize(off, len, Objects.requireNonNull(str, "str").length());
}
- static void checkFromIndexSize(final int off, final int len, final int arrayLength) {
- if ((off | len | arrayLength) < 0 || arrayLength - len < off) {
- throw new IndexOutOfBoundsException(String.format("Range [%s, %The sub-sequence is valid if all of the following hold:
+ *
+ * The sub-sequence is valid if all of the following hold:
+ *
*
- *
{@code fromIndex >= 0}
- *
{@code fromIndex <= toIndex}
- *
{@code toIndex <= seq.length()}
+ *
{@code fromIndex >= 0}
+ *
{@code fromIndex <= toIndex}
+ *
{@code toIndex <= seq.length()}
*
+ *
+ * If {@code seq} is {@code null}, it is treated as the literal string {@code "null"} (length {@code 4}).
+ *
+ *
+ * If the range is invalid, throws {@link IndexOutOfBoundsException} with a descriptive message.
+ *
If {@code seq} is {@code null}, it is treated as the literal string {@code "null"} (length {@code 4}).
- *
- *
If the range is invalid, throws {@link IndexOutOfBoundsException} with a descriptive message.
- *
- *
Typical usage in {@link Appendable#append(CharSequence, int, int)} implementations:
- *
- *
+ *
+ *
* public Appendable append(CharSequence csq, int start, int end) throws IOException {
* IOUtils.checkFromToIndex(csq, start, end);
* // perform append...
* return this;
* }
- *
+ *
+ *
*
- * @param seq the character sequence to validate (may be {@code null}, treated as {@code "null"})
- * @param fromIndex the starting index (inclusive)
- * @param toIndex the ending index (exclusive)
- * @throws IndexOutOfBoundsException if the range {@code [fromIndex, toIndex)} is out of bounds for {@code seq}
+ * @param seq The character sequence to validate (may be {@code null}, treated as {@code "null"}).
+ * @param fromIndex The starting index (inclusive).
+ * @param toIndex The ending index (exclusive).
+ * @throws IndexOutOfBoundsException if the range {@code [fromIndex, toIndex)} is out of bounds for {@code seq}.
* @see Appendable#append(CharSequence, int, int)
* @since 2.21.0
*/
@@ -589,13 +702,12 @@ static void checkFromToIndex(final int fromIndex, final int toIndex, final int l
*
Removes the current thread's value for thread-local variables.
*
Sets static scratch arrays to 0s.
*
+ *
* @see IO#clear()
*/
static void clear() {
- SCRATCH_BYTE_BUFFER_RW.remove();
- SCRATCH_CHAR_BUFFER_RW.remove();
- Arrays.fill(SCRATCH_BYTE_BUFFER_WO, (byte) 0);
- Arrays.fill(SCRATCH_CHAR_BUFFER_WO, (char) 0);
+ ScratchBytes.LOCAL.remove();
+ ScratchChars.LOCAL.remove();
}
/**
@@ -626,8 +738,8 @@ public static void close(final Closeable... closeables) throws IOExceptionList {
* Closes the given {@link Closeable} as a null-safe operation.
*
* @param closeable The resource to close, may be null.
- * @param consumer Consume the IOException thrown by {@link Closeable#close()}.
- * @throws IOException if an I/O error occurs.
+ * @param consumer Consume the IOException thrown by {@link Closeable#close()}.
+ * @throws IOException As thrown by the consumer.
* @since 2.7
*/
public static void close(final Closeable closeable, final IOConsumer consumer) throws IOException {
@@ -635,13 +747,9 @@ public static void close(final Closeable closeable, final IOConsumer) null);
}
/**
* Closes a {@link Closeable} unconditionally.
- *
*
- * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. This is typically used in
- * finally blocks.
+ * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
*
* try {
* return IOUtils.copy(inputStream, outputStream);
@@ -703,12 +811,12 @@ private static void closeQ(final Closeable closeable) {
* Also consider using a try-with-resources statement where appropriate.
*
*
- * @param closeable the objects to close, may be null or already closed.
+ * @param closeable The objects to close, may be null or already closed.
* @since 2.0
* @see Throwable#addSuppressed(Throwable)
*/
public static void closeQuietly(final Closeable closeable) {
- closeQuietly(closeable, null);
+ closeQuietly(closeable, (Consumer) null);
}
/**
@@ -716,17 +824,17 @@ public static void closeQuietly(final Closeable closeable) {
*
* Equivalent to {@link Closeable#close()}, except any exceptions will be ignored.
*
- * This is typically used in finally blocks to ensure that the closeable is closed
- * even if an Exception was thrown before the normal close statement was reached.
- *
- * It should not be used to replace the close statement(s)
- * which should be present for the non-exceptional case.
- *
- * It is only intended to simplify tidying up where normal processing has already failed
- * and reporting close failure as well is not necessary or useful.
+ * This is typically used in finally blocks to ensure that the closeable is closed even if an Exception was thrown before the normal close statement was
+ * reached.
+ *
+ *
+ * It should not be used to replace the close statement(s) which should be present for the non-exceptional case.
+ *
+ * It is only intended to simplify tidying up where normal processing has already failed and reporting close failure as well is not necessary or useful.
*
* Also consider using a try-with-resources statement where appropriate.
*
- * @param closeables the objects to close, may be null or already closed.
+ *
+ * @param closeables The objects to close, may be null or already closed.
* @see #closeQuietly(Closeable)
* @since 2.5
* @see Throwable#addSuppressed(Throwable)
@@ -767,7 +877,7 @@ public static void closeQuietly(final Closeable... closeables) {
* Closes the given {@link Closeable} as a null-safe operation while consuming IOException by the given {@code consumer}.
*
* @param closeable The resource to close, may be null.
- * @param consumer Consumes the Exception thrown by {@link Closeable#close()}.
+ * @param consumer Consumes the Exception thrown by {@link Closeable#close()}.
* @since 2.7
*/
public static void closeQuietly(final Closeable closeable, final Consumer consumer) {
@@ -785,30 +895,30 @@ public static void closeQuietly(final Closeable closeable, final Consumer
- * Equivalent to {@link InputStream#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
+ * Equivalent to {@link InputStream#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
*
*
* Example code:
*
+ *
*
- * byte[] data = new byte[1024];
- * InputStream in = null;
- * try {
- * in = new FileInputStream("foo.txt");
- * in.read(data);
- * in.close(); //close errors are handled
- * } catch (Exception e) {
- * // error handling
- * } finally {
- * IOUtils.closeQuietly(in);
- * }
+ * byte[] data = new byte[1024];
+ * InputStream in = null;
+ * try {
+ * in = new FileInputStream("foo.txt");
+ * in.read(data);
+ * in.close(); // close errors are handled
+ * } catch (Exception e) {
+ * // error handling
+ * } finally {
+ * IOUtils.closeQuietly(in);
+ * }
*
*
* Also consider using a try-with-resources statement where appropriate.
*
*
- * @param input the InputStream to close, may be null or already closed.
+ * @param input The InputStream to close, may be null or already closed.
* @see Throwable#addSuppressed(Throwable)
*/
public static void closeQuietly(final InputStream input) {
@@ -821,7 +931,7 @@ public static void closeQuietly(final InputStream input) {
* Equivalent calling {@link Closeable#close()} on each element, except any exceptions will be ignored.
*
*
- * @param closeables the objects to close, may be null or already closed.
+ * @param closeables The objects to close, may be null or already closed.
* @see #closeQuietly(Closeable)
* @since 2.12.0
*/
@@ -834,20 +944,19 @@ public static void closeQuietly(final Iterable closeables) {
/**
* Closes an {@link OutputStream} unconditionally.
*
- * Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
+ * Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
*
*
* Example code:
*
+ *
*
* byte[] data = "Hello, World".getBytes();
- *
* OutputStream out = null;
* try {
* out = new FileOutputStream("foo.txt");
* out.write(data);
- * out.close(); //close errors are handled
+ * out.close(); // close errors are handled
* } catch (IOException e) {
* // error handling
* } finally {
@@ -858,7 +967,7 @@ public static void closeQuietly(final Iterable closeables) {
* Also consider using a try-with-resources statement where appropriate.
*
*
- * @param output the OutputStream to close, may be null or already closed.
+ * @param output The OutputStream to close, may be null or already closed.
* @see Throwable#addSuppressed(Throwable)
*/
public static void closeQuietly(final OutputStream output) {
@@ -868,30 +977,30 @@ public static void closeQuietly(final OutputStream output) {
/**
* Closes an {@link Reader} unconditionally.
*
- * Equivalent to {@link Reader#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
+ * Equivalent to {@link Reader#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
*
*
* Example code:
*
+ *
*
- * char[] data = new char[1024];
- * Reader in = null;
- * try {
- * in = new FileReader("foo.txt");
- * in.read(data);
- * in.close(); //close errors are handled
- * } catch (Exception e) {
- * // error handling
- * } finally {
- * IOUtils.closeQuietly(in);
- * }
+ * char[] data = new char[1024];
+ * Reader in = null;
+ * try {
+ * in = new FileReader("foo.txt");
+ * in.read(data);
+ * in.close(); // close errors are handled
+ * } catch (Exception e) {
+ * // error handling
+ * } finally {
+ * IOUtils.closeQuietly(in);
+ * }
*
*
* Also consider using a try-with-resources statement where appropriate.
*
*
- * @param reader the Reader to close, may be null or already closed.
+ * @param reader The Reader to close, may be null or already closed.
* @see Throwable#addSuppressed(Throwable)
*/
public static void closeQuietly(final Reader reader) {
@@ -901,29 +1010,28 @@ public static void closeQuietly(final Reader reader) {
/**
* Closes a {@link Selector} unconditionally.
*
- * Equivalent to {@link Selector#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
+ * Equivalent to {@link Selector#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
*
* Also consider using a try-with-resources statement where appropriate.
*
*
- * @param selector the Selector to close, may be null or already closed.
+ * @param selector The Selector to close, may be null or already closed.
* @since 2.2
* @see Throwable#addSuppressed(Throwable)
*/
@@ -934,29 +1042,29 @@ public static void closeQuietly(final Selector selector) {
/**
* Closes a {@link ServerSocket} unconditionally.
*
- * Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
+ * Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
*
* Also consider using a try-with-resources statement where appropriate.
*
*
- * @param serverSocket the ServerSocket to close, may be null or already closed.
+ * @param serverSocket The ServerSocket to close, may be null or already closed.
* @since 2.2
* @see Throwable#addSuppressed(Throwable)
*/
@@ -967,29 +1075,29 @@ public static void closeQuietly(final ServerSocket serverSocket) {
/**
* Closes a {@link Socket} unconditionally.
*
- * Equivalent to {@link Socket#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
+ * Equivalent to {@link Socket#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
*
* Also consider using a try-with-resources statement where appropriate.
*
*
- * @param socket the Socket to close, may be null or already closed.
+ * @param socket The Socket to close, may be null or already closed.
* @since 2.0
* @see Throwable#addSuppressed(Throwable)
*/
@@ -1003,7 +1111,7 @@ public static void closeQuietly(final Socket socket) {
* Equivalent calling {@link Closeable#close()} on each element, except any exceptions will be ignored.
*
*
- * @param closeables the objects to close, may be null or already closed.
+ * @param closeables The objects to close, may be null or already closed.
* @see #closeQuietly(Closeable)
* @since 2.12.0
*/
@@ -1016,45 +1124,76 @@ public static void closeQuietly(final Stream closeables) {
/**
* Closes an {@link Writer} unconditionally.
*
- * Equivalent to {@link Writer#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
+ * Equivalent to {@link Writer#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
*
* Also consider using a try-with-resources statement where appropriate.
*
*
- * @param writer the Writer to close, may be null or already closed.
+ * @param writer The Writer to close, may be null or already closed.
* @see Throwable#addSuppressed(Throwable)
*/
public static void closeQuietly(final Writer writer) {
closeQ(writer);
}
+ /**
+ * Closes a {@link Closeable} unconditionally and adds any exception thrown by the {@code close()} to the given Throwable.
+ *
+ * Also consider using a try-with-resources statement where appropriate.
+ *
+ *
+ * @param The Throwable type.
+ * @param closeable The object to close, may be null or already closed.
+ * @param throwable Add the exception throw by the closeable to the given Throwable.
+ * @return The given Throwable.
+ * @since 2.22.0
+ * @see Throwable#addSuppressed(Throwable)
+ */
+ public static T closeQuietlySuppress(final Closeable closeable, final T throwable) {
+ closeQuietly(closeable, throwable::addSuppressed);
+ return throwable;
+ }
+
/**
* Consumes bytes from a {@link InputStream} and ignores them.
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
*
- * @param input the {@link InputStream} to read.
- * @return the number of bytes copied. or {@code 0} if {@code input is null}.
+ * @param input The {@link InputStream} to read.
+ * @return The number of bytes copied. or {@code 0} if {@code input is null}.
* @throws NullPointerException if the InputStream is {@code null}.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 2.8.0
*/
public static long consume(final InputStream input) throws IOException {
@@ -1067,10 +1206,10 @@ public static long consume(final InputStream input) throws IOException {
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
*
- * @param input the {@link Reader} to read.
- * @return the number of bytes copied. or {@code 0} if {@code input is null}.
+ * @param input The {@link Reader} to read.
+ * @return The number of bytes copied. or {@code 0} if {@code input is null}.
* @throws NullPointerException if the Reader is {@code null}.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 2.12.0
*/
public static long consume(final Reader input) throws IOException {
@@ -1078,18 +1217,15 @@ public static long consume(final Reader input) throws IOException {
}
/**
- * Compares the contents of two Streams to determine if they are equal or
- * not.
+ * Compares the contents of two Streams to determine if they are equal or not.
*
- * This method buffers the input internally using
- * {@link BufferedInputStream} if they are not already buffered.
+ * This method buffers the input internally using {@link BufferedInputStream} if they are not already buffered.
*
*
- * @param input1 the first stream.
- * @param input2 the second stream.
- * @return true if the content of the streams are equal or they both don't.
- * exist, false otherwise.
- * @throws IOException if an I/O error occurs.
+ * @param input1 The first stream.
+ * @param input2 The second stream.
+ * @return true if the content of the streams are equal or they both don't. exist, false otherwise.
+ * @throws IOException if an I/O error occurs.
*/
@SuppressWarnings("resource") // Caller closes input streams
public static boolean contentEquals(final InputStream input1, final InputStream input2) throws IOException {
@@ -1107,10 +1243,7 @@ public static boolean contentEquals(final InputStream input1, final InputStream
// TODO Consider making public
private static boolean contentEquals(final Iterator> iterator1, final Iterator> iterator2) {
while (iterator1.hasNext()) {
- if (!iterator2.hasNext()) {
- return false;
- }
- if (!Objects.equals(iterator1.next(), iterator2.next())) {
+ if (!iterator2.hasNext() || !Objects.equals(iterator1.next(), iterator2.next())) {
return false;
}
}
@@ -1123,11 +1256,11 @@ private static boolean contentEquals(final Iterator> iterator1, final Iterator
* This method buffers the input internally using {@link BufferedReader} if they are not already buffered.
*
*
- * @param input1 the first reader.
- * @param input2 the second reader.
+ * @param input1 The first reader.
+ * @param input2 The second reader.
* @return true if the content of the readers are equal or they both don't exist, false otherwise.
* @throws NullPointerException if either input is null.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 1.1
*/
public static boolean contentEquals(final Reader input1, final Reader input2) throws IOException {
@@ -1137,39 +1270,38 @@ public static boolean contentEquals(final Reader input1, final Reader input2) th
if (input1 == null || input2 == null) {
return false;
}
-
- // reuse one
- final char[] array1 = getScratchCharArray();
- // but allocate another
- final char[] array2 = charArray();
- int pos1;
- int pos2;
- int count1;
- int count2;
- while (true) {
- pos1 = 0;
- pos2 = 0;
- for (int index = 0; index < DEFAULT_BUFFER_SIZE; index++) {
- if (pos1 == index) {
- do {
- count1 = input1.read(array1, pos1, DEFAULT_BUFFER_SIZE - pos1);
- } while (count1 == 0);
- if (count1 == EOF) {
- return pos2 == index && input2.read() == EOF;
+ try (ScratchChars scratch = IOUtils.ScratchChars.get()) {
+ final char[] array1 = scratch.array();
+ final char[] array2 = charArray();
+ int pos1;
+ int pos2;
+ int count1;
+ int count2;
+ while (true) {
+ pos1 = 0;
+ pos2 = 0;
+ for (int index = 0; index < DEFAULT_BUFFER_SIZE; index++) {
+ if (pos1 == index) {
+ do {
+ count1 = input1.read(array1, pos1, DEFAULT_BUFFER_SIZE - pos1);
+ } while (count1 == 0);
+ if (count1 == EOF) {
+ return pos2 == index && input2.read() == EOF;
+ }
+ pos1 += count1;
}
- pos1 += count1;
- }
- if (pos2 == index) {
- do {
- count2 = input2.read(array2, pos2, DEFAULT_BUFFER_SIZE - pos2);
- } while (count2 == 0);
- if (count2 == EOF) {
- return pos1 == index && input1.read() == EOF;
+ if (pos2 == index) {
+ do {
+ count2 = input2.read(array2, pos2, DEFAULT_BUFFER_SIZE - pos2);
+ } while (count2 == 0);
+ if (count2 == EOF) {
+ return pos1 == index && input1.read() == EOF;
+ }
+ pos2 += count2;
+ }
+ if (array1[index] != array2[index]) {
+ return false;
}
- pos2 += count2;
- }
- if (array1[index] != array2[index]) {
- return false;
}
}
}
@@ -1198,16 +1330,14 @@ private static boolean contentEqualsIgnoreEOL(final BufferedReader reader1, fina
}
/**
- * Compares the contents of two Readers to determine if they are equal or
- * not, ignoring EOL characters.
+ * Compares the contents of two Readers to determine if they are equal or not, ignoring EOL characters.
*
- * This method buffers the input internally using
- * {@link BufferedReader} if they are not already buffered.
+ * This method buffers the input internally using {@link BufferedReader} if they are not already buffered.
*
*
- * @param reader1 the first reader.
- * @param reader2 the second reader.
- * @return true if the content of the readers are equal (ignoring EOL differences), false otherwise.
+ * @param reader1 The first reader.
+ * @param reader2 The second reader.
+ * @return true if the content of the readers are equal (ignoring EOL differences), false otherwise.
* @throws NullPointerException if either input is null.
* @throws UncheckedIOException if an I/O error occurs.
* @since 2.2
@@ -1229,17 +1359,16 @@ public static boolean contentEqualsIgnoreEOL(final Reader reader1, final Reader
* This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * Large streams (over 2GB) will return a bytes copied value of {@code -1} after the copy has completed since
- * the correct number of bytes cannot be returned as an int. For large streams use the
- * {@link #copyLarge(InputStream, OutputStream)} method.
+ * Large streams (over 2GB) will return a bytes copied value of {@code -1} after the copy has completed since the correct number of bytes cannot be returned
+ * as an int. For large streams use the {@link #copyLarge(InputStream, OutputStream)} method.
*
*
- * @param inputStream the {@link InputStream} to read.
- * @param outputStream the {@link OutputStream} to write.
- * @return the number of bytes copied, or -1 if greater than {@link Integer#MAX_VALUE}.
+ * @param inputStream The {@link InputStream} to read.
+ * @param outputStream The {@link OutputStream} to write.
+ * @return The number of bytes copied, or -1 if greater than {@link Integer#MAX_VALUE}.
* @throws NullPointerException if the InputStream is {@code null}.
* @throws NullPointerException if the OutputStream is {@code null}.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 1.1
*/
public static int copy(final InputStream inputStream, final OutputStream outputStream) throws IOException {
@@ -1248,19 +1377,18 @@ public static int copy(final InputStream inputStream, final OutputStream outputS
}
/**
- * Copies bytes from an {@link InputStream} to an {@link OutputStream} using an internal buffer of the
- * given size.
+ * Copies bytes from an {@link InputStream} to an {@link OutputStream} using an internal buffer of the given size.
*
* This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param inputStream the {@link InputStream} to read.
- * @param outputStream the {@link OutputStream} to write to.
- * @param bufferSize the bufferSize used to copy from the input to the output.
- * @return the number of bytes copied.
+ * @param inputStream The {@link InputStream} to read.
+ * @param outputStream The {@link OutputStream} to write to.
+ * @param bufferSize The bufferSize used to copy from the input to the output.
+ * @return The number of bytes copied.
* @throws NullPointerException if the InputStream is {@code null}.
* @throws NullPointerException if the OutputStream is {@code null}.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 2.5
*/
public static long copy(final InputStream inputStream, final OutputStream outputStream, final int bufferSize) throws IOException {
@@ -1268,18 +1396,16 @@ public static long copy(final InputStream inputStream, final OutputStream output
}
/**
- * Copies bytes from an {@link InputStream} to chars on a
- * {@link Writer} using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Copies bytes from an {@link InputStream} to chars on a {@link Writer} using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
* This method uses {@link InputStreamReader}.
*
*
- * @param input the {@link InputStream} to read.
- * @param writer the {@link Writer} to write to.
+ * @param input The {@link InputStream} to read.
+ * @param writer The {@link Writer} to write to.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
@@ -1291,19 +1417,17 @@ public static void copy(final InputStream input, final Writer writer) throws IOE
}
/**
- * Copies bytes from an {@link InputStream} to chars on a
- * {@link Writer} using the specified character encoding.
+ * Copies bytes from an {@link InputStream} to chars on a {@link Writer} using the specified character encoding.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
* This method uses {@link InputStreamReader}.
*
*
- * @param input the {@link InputStream} to read.
- * @param writer the {@link Writer} to write to.
- * @param inputCharset the charset to use for the input stream, null means platform default.
+ * @param input The {@link InputStream} to read.
+ * @param writer The {@link Writer} to write to.
+ * @param inputCharset The charset to use for the input stream, null means platform default.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
@@ -1313,23 +1437,20 @@ public static void copy(final InputStream input, final Writer writer, final Char
}
/**
- * Copies bytes from an {@link InputStream} to chars on a
- * {@link Writer} using the specified character encoding.
+ * Copies bytes from an {@link InputStream} to chars on a {@link Writer} using the specified character encoding.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
* This method uses {@link InputStreamReader}.
*
*
- * @param input the {@link InputStream} to read
- * @param writer the {@link Writer} to write to
- * @param inputCharsetName the name of the requested charset for the InputStream, null means platform default.
+ * @param input The {@link InputStream} to read.
+ * @param writer The {@link Writer} to write to.
+ * @param inputCharsetName The name of the requested charset for the InputStream, null means platform default.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
@@ -1342,8 +1463,7 @@ public static void copy(final InputStream input, final Writer writer, final Stri
/**
* Copies bytes from a {@link ByteArrayOutputStream} to a {@link QueueInputStream}.
*
- * Unlike using JDK {@link PipedInputStream} and {@link PipedOutputStream} for this, this
- * solution works safely in a single thread environment.
+ * Unlike using JDK {@link PipedInputStream} and {@link PipedOutputStream} for this, this solution works safely in a single thread environment.
*
*
* Example usage:
@@ -1352,14 +1472,13 @@ public static void copy(final InputStream input, final Writer writer, final Stri
*
*
- * @param outputStream the {@link ByteArrayOutputStream} to read.
- * @return the {@link QueueInputStream} filled with the content of the outputStream.
+ * @param outputStream The {@link ByteArrayOutputStream} to read.
+ * @return The {@link QueueInputStream} filled with the content of the outputStream.
* @throws NullPointerException if the {@link ByteArrayOutputStream} is {@code null}.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 2.12
*/
@SuppressWarnings("resource") // streams are closed by the caller.
@@ -1373,19 +1492,16 @@ public static QueueInputStream copy(final java.io.ByteArrayOutputStream outputSt
/**
* Copies chars from a {@link Reader} to a {@link Appendable}.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedReader}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
- * Large streams (over 2GB) will return a chars copied value of
- * {@code -1} after the copy has completed since the correct
- * number of chars cannot be returned as an int. For large streams
- * use the {@link #copyLarge(Reader, Writer)} method.
+ * Large streams (over 2GB) will return a chars copied value of {@code -1} after the copy has completed since the correct number of chars cannot be returned
+ * as an int. For large streams use the {@link #copyLarge(Reader, Writer)} method.
*
*
- * @param reader the {@link Reader} to read.
- * @param output the {@link Appendable} to write to.
- * @return the number of characters copied, or -1 if > Integer.MAX_VALUE.
+ * @param reader The {@link Reader} to read.
+ * @param output The {@link Appendable} to write to.
+ * @return The number of characters copied, or -1 if > Integer.MAX_VALUE.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 2.7
@@ -1397,14 +1513,13 @@ public static long copy(final Reader reader, final Appendable output) throws IOE
/**
* Copies chars from a {@link Reader} to an {@link Appendable}.
*
- * This method uses the provided buffer, so there is no need to use a
- * {@link BufferedReader}.
+ * This method uses the provided buffer, so there is no need to use a {@link BufferedReader}.
*
*
- * @param reader the {@link Reader} to read.
- * @param output the {@link Appendable} to write to.
- * @param buffer the buffer to be used for the copy.
- * @return the number of characters copied.
+ * @param reader The {@link Reader} to read.
+ * @param output The {@link 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
@@ -1421,7 +1536,7 @@ public static long copy(final Reader reader, final Appendable output, final Char
}
/**
- * Copies chars from a {@link Reader} to bytes on an {@link OutputStream} using the the virtual machine's {@link Charset#defaultCharset() default charset},
+ * Copies chars from a {@link Reader} to bytes on an {@link OutputStream} using the virtual machine's {@linkplain Charset#defaultCharset() default charset},
* and calling flush.
*
* This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
@@ -1433,12 +1548,12 @@ public static long copy(final Reader reader, final Appendable output, final Char
* This method uses {@link OutputStreamWriter}.
*
*
- * @param reader the {@link Reader} to read.
- * @param output the {@link OutputStream} to write to.
+ * @param reader The {@link Reader} to read.
+ * @param output The {@link OutputStream} to write to.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
- * @deprecated Use {@link #copy(Reader, OutputStream, Charset)} instead
+ * @deprecated Use {@link #copy(Reader, OutputStream, Charset)} instead.
*/
@Deprecated
public static void copy(final Reader reader, final OutputStream output) throws IOException {
@@ -1457,9 +1572,9 @@ public static void copy(final Reader reader, final OutputStream output) throws I
* This method uses {@link OutputStreamWriter}.
*
*
- * @param reader the {@link Reader} to read.
- * @param output the {@link OutputStream} to write to.
- * @param outputCharset the charset to use for the OutputStream, null means platform default.
+ * @param reader The {@link Reader} to read.
+ * @param output The {@link OutputStream} to write to.
+ * @param outputCharset The charset to use for the OutputStream, null means platform default.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
@@ -1478,7 +1593,7 @@ public static void copy(final Reader reader, final OutputStream output, final Ch
* This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
- * Character encoding names can be found at IANA.
+ * Character encoding names can be found at IANA.
*
*
* Due to the implementation of OutputStreamWriter, this method performs a flush.
@@ -1487,9 +1602,9 @@ public static void copy(final Reader reader, final OutputStream output, final Ch
* This method uses {@link OutputStreamWriter}.
*
*
- * @param reader the {@link Reader} to read.
- * @param output the {@link OutputStream} to write to.
- * @param outputCharsetName the name of the requested charset for the OutputStream, null means platform default.
+ * @param reader The {@link Reader} to read.
+ * @param output The {@link OutputStream} to write to.
+ * @param outputCharsetName The name of the requested charset for the OutputStream, null means platform default.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
@@ -1502,19 +1617,16 @@ public static void copy(final Reader reader, final OutputStream output, final St
/**
* Copies chars from a {@link Reader} to a {@link Writer}.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedReader}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
- * Large streams (over 2GB) will return a chars copied value of
- * {@code -1} after the copy has completed since the correct
- * number of chars cannot be returned as an int. For large streams
- * use the {@link #copyLarge(Reader, Writer)} method.
+ * Large streams (over 2GB) will return a chars copied value of {@code -1} after the copy has completed since the correct number of chars cannot be returned
+ * as an int. For large streams use the {@link #copyLarge(Reader, Writer)} method.
*
*
- * @param reader the {@link Reader} to read.
- * @param writer the {@link Writer} to write.
- * @return the number of characters copied, or -1 if > Integer.MAX_VALUE.
+ * @param reader The {@link Reader} to read.
+ * @param writer The {@link Writer} to write.
+ * @return The number of characters copied, or -1 if > Integer.MAX_VALUE.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
@@ -1536,12 +1648,12 @@ public static int copy(final Reader reader, final Writer writer) throws IOExcept
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
*
- * @param url the {@link URL} to read.
- * @param file the {@link OutputStream} to write.
- * @return the number of bytes copied.
+ * @param url The {@link URL} to read.
+ * @param file The {@link OutputStream} to write.
+ * @return The number of bytes copied.
* @throws NullPointerException if the URL is {@code null}.
* @throws NullPointerException if the OutputStream is {@code null}.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 2.9.0
*/
public static long copy(final URL url, final File file) throws IOException {
@@ -1559,12 +1671,12 @@ public static long copy(final URL url, final File file) throws IOException {
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
*
- * @param url the {@link URL} to read.
- * @param outputStream the {@link OutputStream} to write.
- * @return the number of bytes copied.
+ * @param url The {@link URL} to read.
+ * @param outputStream The {@link OutputStream} to write.
+ * @return The number of bytes copied.
* @throws NullPointerException if the URL is {@code null}.
* @throws NullPointerException if the OutputStream is {@code null}.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 2.9.0
*/
public static long copy(final URL url, final OutputStream outputStream) throws IOException {
@@ -1574,49 +1686,43 @@ public static long copy(final URL url, final OutputStream outputStream) throws I
}
/**
- * Copies bytes from a large (over 2GB) {@link InputStream} to an
- * {@link OutputStream}.
+ * Copies bytes from a large (over 2GB) {@link InputStream} to an {@link OutputStream}.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
*
- * @param inputStream the {@link InputStream} to read.
- * @param outputStream the {@link OutputStream} to write.
- * @return the number of bytes copied.
+ * @param inputStream The {@link InputStream} to read.
+ * @param outputStream The {@link OutputStream} to write.
+ * @return The number of bytes copied.
* @throws NullPointerException if the InputStream is {@code null}.
* @throws NullPointerException if the OutputStream is {@code null}.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 1.3
*/
- public static long copyLarge(final InputStream inputStream, final OutputStream outputStream)
- throws IOException {
+ public static long copyLarge(final InputStream inputStream, final OutputStream outputStream) throws IOException {
return copy(inputStream, outputStream, DEFAULT_BUFFER_SIZE);
}
/**
- * Copies bytes from a large (over 2GB) {@link InputStream} to an
- * {@link OutputStream}.
+ * Copies bytes from a large (over 2GB) {@link InputStream} to an {@link OutputStream}.
*
- * This method uses the provided buffer, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method uses the provided buffer, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param inputStream the {@link InputStream} to read.
- * @param outputStream the {@link OutputStream} to write.
- * @param buffer the buffer to use for the copy
- * @return the number of bytes copied.
+ * @param inputStream The {@link InputStream} to read.
+ * @param outputStream The {@link OutputStream} to write.
+ * @param buffer The buffer to use for the copy.
+ * @return The number of bytes copied.
* @throws NullPointerException if the InputStream is {@code null}.
* @throws NullPointerException if the OutputStream is {@code null}.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
* @since 2.2
*/
@SuppressWarnings("resource") // streams are closed by the caller.
- public static long copyLarge(final InputStream inputStream, final OutputStream outputStream, final byte[] buffer)
- throws IOException {
+ public static long copyLarge(final InputStream inputStream, final OutputStream outputStream, final byte[] buffer) throws IOException {
Objects.requireNonNull(inputStream, "inputStream");
Objects.requireNonNull(outputStream, "outputStream");
long count = 0;
@@ -1629,58 +1735,53 @@ public static long copyLarge(final InputStream inputStream, final OutputStream o
}
/**
- * Copies some or all bytes from a large (over 2GB) {@link InputStream} to an
- * {@link OutputStream}, optionally skipping input bytes.
+ * Copies some or all bytes from a large (over 2GB) {@link InputStream} to an {@link OutputStream}, optionally skipping input bytes.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * Note that the implementation uses {@link #skip(InputStream, long)}.
- * This means that the method may be considerably less efficient than using the actual skip implementation,
- * this is done to guarantee that the correct number of characters are skipped.
+ * Note that the implementation uses {@link #skip(InputStream, long)}. This means that the method may be considerably less efficient than using the actual
+ * skip implementation, this is done to guarantee that the correct number of characters are skipped.
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
- * @param input the {@link InputStream} to read.
- * @param output the {@link OutputStream} to write.
+ * @param input The {@link InputStream} to read.
+ * @param output The {@link OutputStream} to write.
* @param inputOffset number of bytes to skip from input before copying, these bytes are ignored.
- * @param length number of bytes to copy.
- * @return the number of bytes copied.
+ * @param length number of bytes to copy.
+ * @return The number of bytes copied.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 2.2
*/
- public static long copyLarge(final InputStream input, final OutputStream output, final long inputOffset,
- final long length) throws IOException {
- return copyLarge(input, output, inputOffset, length, getScratchByteArray());
+ public static long copyLarge(final InputStream input, final OutputStream output, final long inputOffset, final long length) throws IOException {
+ try (ScratchBytes scratch = ScratchBytes.get()) {
+ return copyLarge(input, output, inputOffset, length, scratch.array());
+ }
}
/**
- * Copies some or all bytes from a large (over 2GB) {@link InputStream} to an
- * {@link OutputStream}, optionally skipping input bytes.
+ * Copies some or all bytes from a large (over 2GB) {@link InputStream} to an {@link OutputStream}, optionally skipping input bytes.
*
- * This method uses the provided buffer, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method uses the provided buffer, so there is no need to use a {@link BufferedInputStream}.
*
*
- * Note that the implementation uses {@link #skip(InputStream, long)}.
- * This means that the method may be considerably less efficient than using the actual skip implementation,
- * this is done to guarantee that the correct number of characters are skipped.
+ * Note that the implementation uses {@link #skip(InputStream, long)}. This means that the method may be considerably less efficient than using the actual
+ * skip implementation, this is done to guarantee that the correct number of characters are skipped.
*
*
- * @param input the {@link InputStream} to read.
- * @param output the {@link OutputStream} to write.
+ * @param input The {@link InputStream} to read.
+ * @param output The {@link OutputStream} to write.
* @param inputOffset number of bytes to skip from input before copying, these bytes are ignored.
- * @param length number of bytes to copy.
- * @param buffer the buffer to use for the copy.
- * @return the number of bytes copied.
+ * @param length number of bytes to copy.
+ * @param buffer The buffer to use for the copy.
+ * @return The number of bytes copied.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 2.2
*/
- public static long copyLarge(final InputStream input, final OutputStream output,
- final long inputOffset, final long length, final byte[] buffer) throws IOException {
+ public static long copyLarge(final InputStream input, final OutputStream output, final long inputOffset, final long length, final byte[] buffer)
+ throws IOException {
if (inputOffset > 0) {
skipFully(input, inputOffset);
}
@@ -1698,7 +1799,7 @@ public static long copyLarge(final InputStream input, final OutputStream output,
output.write(buffer, 0, read);
totalRead += read;
if (length > 0) { // only adjust length if not reading to the end
- // Note the cast must work because buffer.length is an integer
+ // Note the cast must work because bufferLength = buffer.length is an integer
bytesToRead = (int) Math.min(length - totalRead, bufferLength);
}
}
@@ -1708,37 +1809,37 @@ public static long copyLarge(final InputStream input, final OutputStream output,
/**
* Copies chars from a large (over 2GB) {@link Reader} to a {@link Writer}.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedReader}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
*
- * @param reader the {@link Reader} to source.
- * @param writer the {@link Writer} to target.
- * @return the number of characters copied.
+ * @param reader The {@link Reader} to source.
+ * @param writer The {@link Writer} to target.
+ * @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
*/
public static long copyLarge(final Reader reader, final Writer writer) throws IOException {
- return copyLarge(reader, writer, getScratchCharArray());
+ try (ScratchChars scratch = IOUtils.ScratchChars.get()) {
+ return copyLarge(reader, writer, scratch.array());
+ }
}
/**
* Copies chars from a large (over 2GB) {@link Reader} to a {@link Writer}.
*
- * This method uses the provided buffer, so there is no need to use a
- * {@link BufferedReader}.
+ * This method uses the provided buffer, so there is no need to use a {@link BufferedReader}.
*
*
- * @param reader the {@link Reader} to source.
- * @param writer the {@link Writer} to target.
- * @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
+ * @param reader The {@link Reader} to source.
+ * @param writer The {@link Writer} to target.
+ * @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
*/
public static long copyLarge(final Reader reader, final Writer writer, final char[] buffer) throws IOException {
@@ -1760,17 +1861,19 @@ public static long copyLarge(final Reader reader, final Writer writer, final cha
* The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}.
*
*
- * @param reader the {@link Reader} to read.
- * @param writer the {@link Writer} to write to.
+ * @param reader The {@link Reader} to read.
+ * @param writer The {@link Writer} to write to.
* @param inputOffset number of chars to skip from input before copying -ve values are ignored.
* @param length number of chars to copy. -ve means all.
- * @return the number of chars copied.
+ * @return The number of chars copied.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 2.2
*/
public static long copyLarge(final Reader reader, final Writer writer, final long inputOffset, final long length) throws IOException {
- return copyLarge(reader, writer, inputOffset, length, getScratchCharArray());
+ try (ScratchChars scratch = IOUtils.ScratchChars.get()) {
+ return copyLarge(reader, writer, inputOffset, length, scratch.array());
+ }
}
/**
@@ -1779,12 +1882,12 @@ public static long copyLarge(final Reader reader, final Writer writer, final lon
* This method uses the provided buffer, so there is no need to use a {@link BufferedReader}.
*
*
- * @param reader the {@link Reader} to read.
- * @param writer the {@link Writer} to write to.
+ * @param reader The {@link Reader} to read.
+ * @param writer The {@link Writer} to write to.
* @param inputOffset number of chars to skip from input before copying -ve values are ignored.
* @param length number of chars to copy. -ve means all.
- * @param buffer the buffer to be used for the copy.
- * @return the number of chars copied.
+ * @param buffer The buffer to be used for the copy.
+ * @return The number of chars copied.
* @throws NullPointerException if the input or output is null.
* @throws IOException if an I/O error occurs.
* @since 2.2
@@ -1817,89 +1920,23 @@ public static long copyLarge(final Reader reader, final Writer writer, final lon
* Copies up to {@code size} bytes from the given {@link InputStream} into a new {@link UnsynchronizedByteArrayOutputStream}.
*
* @param input The {@link InputStream} to read; must not be {@code null}.
- * @param limit The maximum number of bytes to read; must be {@code >= 0}.
- * The actual bytes read are validated to equal {@code size}.
+ * @param limit The maximum number of bytes to read; must be {@code >= 0}. The actual bytes read are validated to equal {@code size}.
* @param bufferSize The buffer size of the output stream; must be {@code > 0}.
- * @return a ByteArrayOutputStream containing the read bytes.
- */
- static UnsynchronizedByteArrayOutputStream copyToOutputStream(
- final InputStream input, final long limit, final int bufferSize) throws IOException {
- try (UnsynchronizedByteArrayOutputStream output = UnsynchronizedByteArrayOutputStream.builder()
- .setBufferSize(bufferSize)
- .get();
- InputStream boundedInput = BoundedInputStream.builder()
- .setMaxCount(limit)
- .setPropagateClose(false)
- .setInputStream(input)
- .get()) {
+ * @return A ByteArrayOutputStream containing the read bytes.
+ */
+ static UnsynchronizedByteArrayOutputStream copyToOutputStream(final InputStream input, final long limit, final int bufferSize) throws IOException {
+ try (UnsynchronizedByteArrayOutputStream output = UnsynchronizedByteArrayOutputStream.builder().setBufferSize(bufferSize).get();
+ InputStream boundedInput = BoundedInputStream.builder().setMaxCount(limit).setPropagateClose(false).setInputStream(input).get()) {
output.write(boundedInput);
return output;
}
}
- /**
- * Fills the given array with 0s.
- *
- * @param arr The non-null array to fill.
- * @return The given array.
- */
- private static byte[] fill0(final byte[] arr) {
- Arrays.fill(arr, (byte) 0);
- return arr;
- }
-
- /**
- * Fills the given array with 0s.
- *
- * @param arr The non-null array to fill.
- * @return The given array.
- */
- private static char[] fill0(final char[] arr) {
- Arrays.fill(arr, (char) 0);
- return arr;
- }
-
- /**
- * Gets the internal byte array buffer, intended for both reading and writing.
- *
- * @return the internal byte array buffer, intended for both reading and writing.
- */
- static byte[] getScratchByteArray() {
- return fill0(SCRATCH_BYTE_BUFFER_RW.get());
- }
-
- /**
- * Gets the internal byte array intended for write only operations.
- *
- * @return the internal byte array intended for write only operations.
- */
- static byte[] getScratchByteArrayWriteOnly() {
- return fill0(SCRATCH_BYTE_BUFFER_WO);
- }
-
- /**
- * Gets the char byte array buffer, intended for both reading and writing.
- *
- * @return the char byte array buffer, intended for both reading and writing.
- */
- static char[] getScratchCharArray() {
- return fill0(SCRATCH_CHAR_BUFFER_RW.get());
- }
-
- /**
- * Gets the internal char array intended for write only operations.
- *
- * @return the internal char array intended for write only operations.
- */
- static char[] getScratchCharArrayWriteOnly() {
- return fill0(SCRATCH_CHAR_BUFFER_WO);
- }
-
/**
* Returns the length of the given array in a null-safe manner.
*
- * @param array an array or null.
- * @return the array length, or 0 if the given array is null.
+ * @param array An array or null.
+ * @return The array length, or 0 if the given array is null.
* @since 2.7
*/
public static int length(final byte[] array) {
@@ -1909,8 +1946,8 @@ public static int length(final byte[] array) {
/**
* Returns the length of the given array in a null-safe manner.
*
- * @param array an array or null.
- * @return the array length, or 0 if the given array is null.
+ * @param array An array or null.
+ * @return The array length, or 0 if the given array is null.
* @since 2.7
*/
public static int length(final char[] array) {
@@ -1920,8 +1957,8 @@ public static int length(final char[] array) {
/**
* Returns the length of the given CharSequence in a null-safe manner.
*
- * @param csq a CharSequence or null.
- * @return the CharSequence length, or 0 if the given CharSequence is null.
+ * @param csq A CharSequence or null.
+ * @return The CharSequence length, or 0 if the given CharSequence is null.
* @since 2.7
*/
public static int length(final CharSequence csq) {
@@ -1931,8 +1968,8 @@ public static int length(final CharSequence csq) {
/**
* Returns the length of the given array in a null-safe manner.
*
- * @param array an array or null.
- * @return the array length, or 0 if the given array is null.
+ * @param array An array or null.
+ * @return The array length, or 0 if the given array is null.
* @since 2.7
*/
public static int length(final Object[] array) {
@@ -1940,33 +1977,31 @@ public static int length(final Object[] array) {
}
/**
- * Returns an Iterator for the lines in an {@link InputStream}, using
- * the character encoding specified (or default encoding if null).
+ * Returns an Iterator for the lines in an {@link InputStream}, using the character encoding specified (or default encoding if null).
*
- * {@link LineIterator} holds a reference to the open
- * {@link InputStream} specified here. When you have finished with
- * the iterator you should close the stream to free internal resources.
- * This can be done by using a try-with-resources block, closing the stream directly, or by calling
+ * {@link LineIterator} holds a reference to the open {@link InputStream} specified here. When you have finished with the iterator you should close the
+ * stream to free internal resources. This can be done by using a try-with-resources block, closing the stream directly, or by calling
* {@link LineIterator#close()}.
*
*
* The recommended usage pattern is:
*
+ *
*
* try {
- * LineIterator it = IOUtils.lineIterator(stream, charset);
- * while (it.hasNext()) {
- * String line = it.nextLine();
- * /// do something with line
- * }
+ * LineIterator it = IOUtils.lineIterator(stream, charset);
+ * while (it.hasNext()) {
+ * String line = it.nextLine();
+ * /// do something with line
+ * }
* } finally {
- * IOUtils.closeQuietly(stream);
+ * IOUtils.closeQuietly(stream);
* }
*
*
- * @param input the {@link InputStream} to read, not null.
- * @param charset the charset to use, null means platform default.
- * @return an Iterator of the lines in the reader, never null.
+ * @param input The {@link InputStream} to read, not null.
+ * @param charset The charset to use, null means platform default.
+ * @return An Iterator of the lines in the reader, never null.
* @throws IllegalArgumentException if the input is null.
* @since 2.3
*/
@@ -1975,33 +2010,31 @@ public static LineIterator lineIterator(final InputStream input, final Charset c
}
/**
- * Returns an Iterator for the lines in an {@link InputStream}, using
- * the character encoding specified (or default encoding if null).
+ * Returns an Iterator for the lines in an {@link InputStream}, using the character encoding specified (or default encoding if null).
*
- * {@link LineIterator} holds a reference to the open
- * {@link InputStream} specified here. When you have finished with
- * the iterator you should close the stream to free internal resources.
- * This can be done by using a try-with-resources block, closing the stream directly, or by calling
+ * {@link LineIterator} holds a reference to the open {@link InputStream} specified here. When you have finished with the iterator you should close the
+ * stream to free internal resources. This can be done by using a try-with-resources block, closing the stream directly, or by calling
* {@link LineIterator#close()}.
*
*
* The recommended usage pattern is:
*
+ *
*
* try {
- * LineIterator it = IOUtils.lineIterator(stream, StandardCharsets.UTF_8.name());
- * while (it.hasNext()) {
- * String line = it.nextLine();
- * /// do something with line
- * }
+ * LineIterator it = IOUtils.lineIterator(stream, StandardCharsets.UTF_8.name());
+ * while (it.hasNext()) {
+ * String line = it.nextLine();
+ * /// do something with line
+ * }
* } finally {
- * IOUtils.closeQuietly(stream);
+ * IOUtils.closeQuietly(stream);
* }
*
*
- * @param input the {@link InputStream} to read, not null.
- * @param charsetName the encoding to use, null means platform default.
- * @return an Iterator of the lines in the reader, never null.
+ * @param input The {@link InputStream} to read, not null.
+ * @param charsetName The encoding to use, null means platform default.
+ * @return An Iterator of the lines in the reader, never null.
* @throws IllegalArgumentException if the input is null.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
* @since 1.2
@@ -2013,29 +2046,27 @@ public static LineIterator lineIterator(final InputStream input, final String ch
/**
* Returns an Iterator for the lines in a {@link Reader}.
*
- * {@link LineIterator} holds a reference to the open
- * {@link Reader} specified here. When you have finished with the
- * iterator you should close the reader to free internal resources.
- * This can be done by using a try-with-resources block, closing the reader directly, or by calling
- * {@link LineIterator#close()}.
+ * {@link LineIterator} holds a reference to the open {@link Reader} specified here. When you have finished with the iterator you should close the reader to
+ * free internal resources. This can be done by using a try-with-resources block, closing the reader directly, or by calling {@link LineIterator#close()}.
*
*
* The recommended usage pattern is:
*
+ *
*
* try {
- * LineIterator it = IOUtils.lineIterator(reader);
- * while (it.hasNext()) {
- * String line = it.nextLine();
- * /// do something with line
- * }
+ * LineIterator it = IOUtils.lineIterator(reader);
+ * while (it.hasNext()) {
+ * String line = it.nextLine();
+ * /// do something with line
+ * }
* } finally {
- * IOUtils.closeQuietly(reader);
+ * IOUtils.closeQuietly(reader);
* }
*
*
- * @param reader the {@link Reader} to read, not null.
- * @return an Iterator of the lines in the reader, never null.
+ * @param reader The {@link Reader} to read, not null.
+ * @return An Iterator of the lines in the reader, never null.
* @throws NullPointerException if the reader is null.
* @since 1.2
*/
@@ -2046,15 +2077,15 @@ public static LineIterator lineIterator(final Reader reader) {
/**
* Reads bytes from an input stream.
*
- * This implementation guarantees that it will read as many bytes
- * as possible before giving up; this may not always be the case for
- * subclasses of {@link InputStream}.
+ * This implementation guarantees that it will read as many bytes as possible before giving up; this may not always be the case for subclasses of
+ * {@link InputStream}.
*
*
- * @param input where to read input from.
+ * @param input where to read input from.
* @param buffer destination.
* @return actual length read; may be less than requested if EOF was reached.
- * @throws IOException if a read error occurs.
+ * @throws NullPointerException if {@code input} or {@code buffer} is null.
+ * @throws IOException if a read error occurs.
* @since 2.2
*/
public static int read(final InputStream input, final byte[] buffer) throws IOException {
@@ -2064,50 +2095,26 @@ public static int read(final InputStream input, final byte[] buffer) throws IOEx
/**
* Reads bytes from an input stream.
*
- * This implementation guarantees that it will read as many bytes
- * as possible before giving up; this may not always be the case for
- * subclasses of {@link InputStream}.
+ * This implementation guarantees that it will read as many bytes as possible before giving up; this may not always be the case for subclasses of
+ * {@link InputStream}.
*
*
- * @param input where to read input.
- * @param buffer destination.
- * @param offset initial offset into buffer.
- * @param length length to read, must be >= 0.
- * @return actual length read; may be less than requested if EOF was reached.
- * @throws IllegalArgumentException if length is negative.
- * @throws IOException if a read error occurs.
- * @since 2.2
- */
- public static int read(final InputStream input, final byte[] buffer, final int offset, final int length)
- throws IOException {
- if (length == 0) {
- return 0;
- }
- return read(input::read, buffer, offset, length);
- }
-
- /**
- * Reads bytes from an input. This implementation guarantees that it will read as many bytes as possible before giving up; this may not always be the case
- * for subclasses of {@link InputStream}.
- *
- * @param input How to read input.
+ * @param input where to read input.
* @param buffer destination.
* @param offset initial offset into buffer.
* @param length length to read, must be >= 0.
* @return actual length read; may be less than requested if EOF was reached.
- * @throws IllegalArgumentException if length is negative.
- * @throws IOException if a read error occurs.
+ * @throws NullPointerException if {@code input} or {@code buffer} is null.
+ * @throws IndexOutOfBoundsException if {@code offset} or {@code length} is negative, or if {@code offset + length} is greater than {@code buffer.length}.
+ * @throws IOException if a read error occurs.
* @since 2.2
*/
- static int read(final IOTriFunction input, final byte[] buffer, final int offset, final int length)
- throws IOException {
- if (length < 0) {
- throw new IllegalArgumentException("Length must not be negative: " + length);
- }
+ public static int read(final InputStream input, final byte[] buffer, final int offset, final int length) throws IOException {
+ checkFromIndexSize(buffer, offset, length);
int remaining = length;
while (remaining > 0) {
final int location = length - remaining;
- final int count = input.apply(buffer, offset + location, remaining);
+ final int count = input.read(buffer, offset + location, remaining);
if (EOF == count) {
break;
}
@@ -2119,14 +2126,13 @@ static int read(final IOTriFunction input, fi
/**
* Reads bytes from a ReadableByteChannel.
*
- * This implementation guarantees that it will read as many bytes
- * as possible before giving up; this may not always be the case for
- * subclasses of {@link ReadableByteChannel}.
+ * This implementation guarantees that it will read as many bytes as possible before giving up; this may not always be the case for subclasses of
+ * {@link ReadableByteChannel}.
*
*
- * @param input the byte channel to read.
+ * @param input The byte channel to read.
* @param buffer byte buffer destination.
- * @return the actual length read; may be less than requested if EOF was reached.
+ * @return The actual length read; may be less than requested if EOF was reached.
* @throws IOException if a read error occurs.
* @since 2.5
*/
@@ -2144,9 +2150,8 @@ public static int read(final ReadableByteChannel input, final ByteBuffer buffer)
/**
* Reads characters from an input character stream.
*
- * This implementation guarantees that it will read as many characters
- * as possible before giving up; this may not always be the case for
- * subclasses of {@link Reader}.
+ * This implementation guarantees that it will read as many characters as possible before giving up; this may not always be the case for subclasses of
+ * {@link Reader}.
*
*
* @param reader where to read input from.
@@ -2162,9 +2167,8 @@ public static int read(final Reader reader, final char[] buffer) throws IOExcept
/**
* Reads characters from an input character stream.
*
- * This implementation guarantees that it will read as many characters
- * as possible before giving up; this may not always be the case for
- * subclasses of {@link Reader}.
+ * This implementation guarantees that it will read as many characters as possible before giving up; this may not always be the case for subclasses of
+ * {@link Reader}.
*
*
* @param reader where to read input from.
@@ -2172,15 +2176,13 @@ public static int read(final Reader reader, final char[] buffer) throws IOExcept
* @param offset initial offset into buffer.
* @param length length to read, must be >= 0.
* @return actual length read; may be less than requested if EOF was reached.
- * @throws IllegalArgumentException if length is negative.
- * @throws IOException if a read error occurs.
+ * @throws NullPointerException if {@code reader} or {@code buffer} is null.
+ * @throws IndexOutOfBoundsException if {@code offset} or {@code length} is negative, or if {@code offset + length} is greater than {@code buffer.length}.
+ * @throws IOException if a read error occurs.
* @since 2.2
*/
- public static int read(final Reader reader, final char[] buffer, final int offset, final int length)
- throws IOException {
- if (length < 0) {
- throw new IllegalArgumentException("Length must not be negative: " + length);
- }
+ public static int read(final Reader reader, final char[] buffer, final int offset, final int length) throws IOException {
+ checkFromIndexSize(buffer, offset, length);
int remaining = length;
while (remaining > 0) {
final int location = length - remaining;
@@ -2196,15 +2198,15 @@ public static int read(final Reader reader, final char[] buffer, final int offse
/**
* Reads the requested number of bytes or fail if there are not enough left.
*
- * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may
- * not read as many bytes as requested (most likely because of reaching EOF).
+ * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may not read as many bytes as requested (most likely because of reaching
+ * EOF).
*
*
- * @param input where to read input from.
+ * @param input where to read input from.
* @param buffer destination.
- * @throws IOException if there is a problem reading the file.
- * @throws IllegalArgumentException if length is negative.
- * @throws EOFException if the number of bytes read was incorrect.
+ * @throws NullPointerException if {@code input} or {@code buffer} is null.
+ * @throws EOFException if the number of bytes read was incorrect.
+ * @throws IOException if there is a problem reading the file.
* @since 2.2
*/
public static void readFully(final InputStream input, final byte[] buffer) throws IOException {
@@ -2214,21 +2216,21 @@ public static void readFully(final InputStream input, final byte[] buffer) throw
/**
* Reads the requested number of bytes or fail if there are not enough left.
*
- * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may
- * not read as many bytes as requested (most likely because of reaching EOF).
+ * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may not read as many bytes as requested (most likely because of reaching
+ * EOF).
*
*
- * @param input where to read input from.
+ * @param input where to read input from.
* @param buffer destination.
* @param offset initial offset into buffer.
* @param length length to read, must be >= 0.
- * @throws IOException if there is a problem reading the file.
- * @throws IllegalArgumentException if length is negative.
- * @throws EOFException if the number of bytes read was incorrect.
+ * @throws NullPointerException if {@code input} or {@code buffer} is null.
+ * @throws IndexOutOfBoundsException if {@code offset} or {@code length} is negative, or if {@code offset + length} is greater than {@code buffer.length}.
+ * @throws EOFException if the number of bytes read was incorrect.
+ * @throws IOException if there is a problem reading the file.
* @since 2.2
*/
- public static void readFully(final InputStream input, final byte[] buffer, final int offset, final int length)
- throws IOException {
+ public static void readFully(final InputStream input, final byte[] buffer, final int offset, final int length) throws IOException {
final int actual = read(input, buffer, offset, length);
if (actual != length) {
throw new EOFException("Length to read: " + length + " actual: " + actual);
@@ -2238,13 +2240,13 @@ public static void readFully(final InputStream input, final byte[] buffer, final
/**
* Reads the requested number of bytes or fail if there are not enough left.
*
- * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may
- * not read as many bytes as requested (most likely because of reaching EOF).
+ * This allows for the possibility that {@link InputStream#read(byte[], int, int)} may not read as many bytes as requested (most likely because of reaching
+ * EOF).
*
*
- * @param input where to read input from.
+ * @param input where to read input from.
* @param length length to read, must be >= 0.
- * @return the bytes read from input.
+ * @return The bytes read from input.
* @throws IOException if there is a problem reading the file.
* @throws IllegalArgumentException if length is negative.
* @throws EOFException if the number of bytes read was incorrect.
@@ -2259,11 +2261,11 @@ public static byte[] readFully(final InputStream input, final int length) throws
/**
* Reads the requested number of bytes or fail if there are not enough left.
*
- * This allows for the possibility that {@link ReadableByteChannel#read(ByteBuffer)} may
- * not read as many bytes as requested (most likely because of reaching EOF).
+ * This allows for the possibility that {@link ReadableByteChannel#read(ByteBuffer)} may not read as many bytes as requested (most likely because of
+ * reaching EOF).
*
*
- * @param input the byte channel to read.
+ * @param input The byte channel to read.
* @param buffer byte buffer destination.
* @throws IOException if there is a problem reading the file.
* @throws EOFException if the number of bytes read was incorrect.
@@ -2280,15 +2282,15 @@ public static void readFully(final ReadableByteChannel input, final ByteBuffer b
/**
* Reads the requested number of characters or fail if there are not enough left.
*
- * This allows for the possibility that {@link Reader#read(char[], int, int)} may
- * not read as many characters as requested (most likely because of reaching EOF).
+ * This allows for the possibility that {@link Reader#read(char[], int, int)} may not read as many characters as requested (most likely because of reaching
+ * EOF).
*
*
* @param reader where to read input from.
* @param buffer destination.
- * @throws IOException if there is a problem reading the file.
- * @throws IllegalArgumentException if length is negative.
- * @throws EOFException if the number of characters read was incorrect.
+ * @throws NullPointerException if {@code reader} or {@code buffer} is null.
+ * @throws EOFException if the number of characters read was incorrect.
+ * @throws IOException if there is a problem reading the file.
* @since 2.2
*/
public static void readFully(final Reader reader, final char[] buffer) throws IOException {
@@ -2298,21 +2300,21 @@ public static void readFully(final Reader reader, final char[] buffer) throws IO
/**
* Reads the requested number of characters or fail if there are not enough left.
*
- * This allows for the possibility that {@link Reader#read(char[], int, int)} may
- * not read as many characters as requested (most likely because of reaching EOF).
+ * This allows for the possibility that {@link Reader#read(char[], int, int)} may not read as many characters as requested (most likely because of reaching
+ * EOF).
*
*
* @param reader where to read input from.
* @param buffer destination.
* @param offset initial offset into buffer.
* @param length length to read, must be >= 0.
- * @throws IOException if there is a problem reading the file.
- * @throws IllegalArgumentException if length is negative.
- * @throws EOFException if the number of characters read was incorrect.
+ * @throws NullPointerException if {@code reader} or {@code buffer} is null.
+ * @throws IndexOutOfBoundsException if {@code offset} or {@code length} is negative, or if {@code offset + length} is greater than {@code buffer.length}.
+ * @throws EOFException if the number of characters read was incorrect.
+ * @throws IOException if there is a problem reading the file.
* @since 2.2
*/
- public static void readFully(final Reader reader, final char[] buffer, final int offset, final int length)
- throws IOException {
+ public static void readFully(final Reader reader, final char[] buffer, final int offset, final int length) throws IOException {
final int actual = read(reader, buffer, offset, length);
if (actual != length) {
throw new EOFException("Length to read: " + length + " actual: " + actual);
@@ -2322,8 +2324,8 @@ public static void readFully(final Reader reader, final char[] buffer, final int
/**
* Gets the contents of a {@link CharSequence} as a list of Strings, one entry per line.
*
- * @param csq the {@link CharSequence} to read, not null.
- * @return the list of Strings, never null.
+ * @param csq The {@link CharSequence} to read, not null.
+ * @return The list of Strings, never null.
* @throws UncheckedIOException if an I/O error occurs.
* @since 2.18.0
*/
@@ -2334,19 +2336,18 @@ public static List readLines(final CharSequence csq) throws UncheckedIOE
}
/**
- * Gets the contents of an {@link InputStream} as a list of Strings,
- * one entry per line, using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Gets the contents of an {@link InputStream} as a list of Strings, one entry per line, using the virtual machine's {@linkplain Charset#defaultCharset()
+ * default charset}.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param input the {@link InputStream} to read, not null.
- * @return the list of Strings, never null.
+ * @param input The {@link InputStream} to read, not null.
+ * @return The list of Strings, never null.
* @throws NullPointerException if the input is null.
* @throws UncheckedIOException if an I/O error occurs.
* @since 1.1
- * @deprecated Use {@link #readLines(InputStream, Charset)} instead
+ * @deprecated Use {@link #readLines(InputStream, Charset)} instead.
*/
@Deprecated
public static List readLines(final InputStream input) throws UncheckedIOException {
@@ -2354,16 +2355,14 @@ public static List readLines(final InputStream input) throws UncheckedIO
}
/**
- * Gets the contents of an {@link InputStream} as a list of Strings,
- * one entry per line, using the specified character encoding.
+ * Gets the contents of an {@link InputStream} as a list of Strings, one entry per line, using the specified character encoding.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param input the {@link InputStream} to read, not null.
- * @param charset the charset to use, null means platform default.
- * @return the list of Strings, never null.
+ * @param input The {@link InputStream} to read, not null.
+ * @param charset The charset to use, null means platform default.
+ * @return The list of Strings, never null.
* @throws NullPointerException if the input is null.
* @throws UncheckedIOException if an I/O error occurs.
* @since 2.3
@@ -2373,20 +2372,17 @@ public static List readLines(final InputStream input, final Charset char
}
/**
- * Gets the contents of an {@link InputStream} as a list of Strings,
- * one entry per line, using the specified character encoding.
+ * Gets the contents of an {@link InputStream} as a list of Strings, one entry per line, using the specified character encoding.
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param input the {@link InputStream} to read, not null.
- * @param charsetName the name of the requested charset, null means platform default.
- * @return the list of Strings, never null.
+ * @param input The {@link InputStream} to read, not null.
+ * @param charsetName The name of the requested charset, null means platform default.
+ * @return The list of Strings, never null.
* @throws NullPointerException if the input is null.
* @throws UncheckedIOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
@@ -2397,15 +2393,13 @@ public static List readLines(final InputStream input, final String chars
}
/**
- * Gets the contents of a {@link Reader} as a list of Strings,
- * one entry per line.
+ * Gets the contents of a {@link Reader} as a list of Strings, one entry per line.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedReader}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
- * @param reader the {@link Reader} to read, not null.
- * @return the list of Strings, never null.
+ * @param reader The {@link Reader} to read, not null.
+ * @return The list of Strings, never null.
* @throws NullPointerException if the input is null.
* @throws UncheckedIOException if an I/O error occurs.
* @since 1.1
@@ -2422,7 +2416,7 @@ public static List readLines(final Reader reader) throws UncheckedIOExce
*
*
* @param name The resource name.
- * @return the requested byte array.
+ * @return The requested byte array.
* @throws IOException if an I/O error occurs or the resource is not found.
* @see #resourceToByteArray(String, ClassLoader)
* @since 2.6
@@ -2437,9 +2431,9 @@ public static byte[] resourceToByteArray(final String name) throws IOException {
* Delegates to {@link #resourceToURL(String, ClassLoader)}.
*
*
- * @param name The resource name.
- * @param classLoader the class loader that the resolution of the resource is delegated to.
- * @return the requested byte array.
+ * @param name The resource name.
+ * @param classLoader The class loader that the resolution of the resource is delegated to.
+ * @return The requested byte array.
* @throws IOException if an I/O error occurs or the resource is not found.
* @see #resourceToURL(String, ClassLoader)
* @since 2.6
@@ -2454,9 +2448,9 @@ public static byte[] resourceToByteArray(final String name, final ClassLoader cl
* Delegates to {@link #resourceToString(String, Charset, ClassLoader) resourceToString(String, Charset, null)}.
*
*
- * @param name The resource name.
- * @param charset the charset to use, null means platform default.
- * @return the requested String.
+ * @param name The resource name.
+ * @param charset The charset to use, null means platform default.
+ * @return The requested String.
* @throws IOException if an I/O error occurs or the resource is not found.
* @see #resourceToString(String, Charset, ClassLoader)
* @since 2.6
@@ -2471,10 +2465,10 @@ public static String resourceToString(final String name, final Charset charset)
* Delegates to {@link #resourceToURL(String, ClassLoader)}.
*
*
- * @param name The resource name.
- * @param charset the Charset to use, null means platform default.
- * @param classLoader the class loader that the resolution of the resource is delegated to.
- * @return the requested String.
+ * @param name The resource name.
+ * @param charset The Charset to use, null means platform default.
+ * @param classLoader The class loader that the resolution of the resource is delegated to.
+ * @return The requested String.
* @throws IOException if an I/O error occurs.
* @see #resourceToURL(String, ClassLoader)
* @since 2.6
@@ -2501,11 +2495,11 @@ public static URL resourceToURL(final String name) throws IOException {
/**
* Gets a URL pointing to the given resource.
*
- * If the {@code classLoader} is not null, call {@link ClassLoader#getResource(String)}, otherwise call
- * {@link Class#getResource(String) IOUtils.class.getResource(name)}.
+ * If the {@code classLoader} is not null, call {@link ClassLoader#getResource(String)}, otherwise call {@link Class#getResource(String)
+ * IOUtils.class.getResource(name)}.
*
*
- * @param name The resource name.
+ * @param name The resource name.
* @param classLoader Delegate to this class loader if not null.
* @return A URL object for reading the resource.
* @throws IOException if the resource is not found.
@@ -2543,7 +2537,9 @@ public static URL resourceToURL(final String name, final ClassLoader classLoader
* @since 2.0
*/
public static long skip(final InputStream input, final long skip) throws IOException {
- return skip(input, skip, IOUtils::getScratchByteArrayWriteOnly);
+ try (ScratchBytes scratch = ScratchBytes.get()) {
+ return skip(input, skip, scratch::array);
+ }
}
/**
@@ -2563,7 +2559,7 @@ public static long skip(final InputStream input, final long skip) throws IOExcep
*
*
* @param input byte stream to skip.
- * @param skip number of bytes to skip.
+ * @param skip number of bytes to skip.
* @param skipBufferSupplier Supplies the buffer to use for reading.
* @return number of bytes actually skipped.
* @throws IOException if there is a problem reading the file.
@@ -2595,11 +2591,9 @@ public static long skip(final InputStream input, final long skip, final Supplier
}
/**
- * Skips bytes from a ReadableByteChannel.
- * This implementation guarantees that it will read as many bytes
- * as possible before giving up.
+ * Skips bytes from a ReadableByteChannel. This implementation guarantees that it will read as many bytes as possible before giving up.
*
- * @param input ReadableByteChannel to skip.
+ * @param input ReadableByteChannel to skip.
* @param toSkip number of bytes to skip.
* @return number of bytes actually skipped.
* @throws IOException if there is a problem reading the ReadableByteChannel.
@@ -2625,15 +2619,12 @@ public static long skip(final ReadableByteChannel input, final long toSkip) thro
}
/**
- * Skips characters from an input character stream.
- * This implementation guarantees that it will read as many characters
- * as possible before giving up; this may not always be the case for
- * skip() implementations in subclasses of {@link Reader}.
+ * Skips characters from an input character stream. This implementation guarantees that it will read as many characters as possible before giving up; this
+ * may not always be the case for skip() implementations in subclasses of {@link Reader}.
*
- * Note that the implementation uses {@link Reader#read(char[], int, int)} rather
- * than delegating to {@link Reader#skip(long)}.
- * This means that the method may be considerably less efficient than using the actual skip implementation,
- * this is done to guarantee that the correct number of characters are skipped.
+ * Note that the implementation uses {@link Reader#read(char[], int, int)} rather than delegating to {@link Reader#skip(long)}. This means that the method
+ * may be considerably less efficient than using the actual skip implementation, this is done to guarantee that the correct number of characters are
+ * skipped.
*
*
* @param reader character stream to skip.
@@ -2650,14 +2641,16 @@ public static long skip(final Reader reader, final long toSkip) throws IOExcepti
throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
}
long remain = toSkip;
- while (remain > 0) {
- // See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
- final char[] charArray = getScratchCharArrayWriteOnly();
- final long n = reader.read(charArray, 0, (int) Math.min(remain, charArray.length));
- if (n < 0) { // EOF
- break;
+ try (ScratchChars scratch = IOUtils.ScratchChars.get()) {
+ final char[] chars = scratch.array();
+ while (remain > 0) {
+ // See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
+ final long n = reader.read(chars, 0, (int) Math.min(remain, chars.length));
+ if (n < 0) { // EOF
+ break;
+ }
+ remain -= n;
}
- remain -= n;
}
return toSkip - remain;
}
@@ -2665,17 +2658,15 @@ public static long skip(final Reader reader, final long toSkip) throws IOExcepti
/**
* Skips the requested number of bytes or fail if there are not enough left.
*
- * This allows for the possibility that {@link InputStream#skip(long)} may
- * not skip as many bytes as requested (most likely because of reaching EOF).
+ * This allows for the possibility that {@link InputStream#skip(long)} may not skip as many bytes as requested (most likely because of reaching EOF).
*
*
- * Note that the implementation uses {@link #skip(InputStream, long)}.
- * This means that the method may be considerably less efficient than using the actual skip implementation,
- * this is done to guarantee that the correct number of characters are skipped.
+ * Note that the implementation uses {@link #skip(InputStream, long)}. This means that the method may be considerably less efficient than using the actual
+ * skip implementation, this is done to guarantee that the correct number of characters are skipped.
*
*
- * @param input stream to skip.
- * @param toSkip the number of bytes to skip.
+ * @param input stream to skip.
+ * @param toSkip The number of bytes to skip.
* @throws IOException if there is a problem reading the file.
* @throws IllegalArgumentException if toSkip is negative.
* @throws EOFException if the number of bytes skipped was incorrect.
@@ -2683,7 +2674,7 @@ public static long skip(final Reader reader, final long toSkip) throws IOExcepti
* @since 2.0
*/
public static void skipFully(final InputStream input, final long toSkip) throws IOException {
- final long skipped = skip(input, toSkip, IOUtils::getScratchByteArrayWriteOnly);
+ final long skipped = skip(input, toSkip);
if (skipped != toSkip) {
throw new EOFException("Bytes to skip: " + toSkip + " actual: " + skipped);
}
@@ -2704,7 +2695,7 @@ public static void skipFully(final InputStream input, final long toSkip) throws
*
*
* @param input stream to skip.
- * @param toSkip the number of bytes to skip.
+ * @param toSkip The number of bytes to skip.
* @param skipBufferSupplier Supplies the buffer to use for reading.
* @throws IOException if there is a problem reading the file.
* @throws IllegalArgumentException if toSkip is negative.
@@ -2725,8 +2716,8 @@ public static void skipFully(final InputStream input, final long toSkip, final S
/**
* Skips the requested number of bytes or fail if there are not enough left.
*
- * @param input ReadableByteChannel to skip.
- * @param toSkip the number of bytes to skip.
+ * @param input ReadableByteChannel to skip.
+ * @param toSkip The number of bytes to skip.
* @throws IOException if there is a problem reading the ReadableByteChannel.
* @throws IllegalArgumentException if toSkip is negative.
* @throws EOFException if the number of bytes skipped was incorrect.
@@ -2745,17 +2736,15 @@ public static void skipFully(final ReadableByteChannel input, final long toSkip)
/**
* Skips the requested number of characters or fail if there are not enough left.
*
- * This allows for the possibility that {@link Reader#skip(long)} may
- * not skip as many characters as requested (most likely because of reaching EOF).
+ * This allows for the possibility that {@link Reader#skip(long)} may not skip as many characters as requested (most likely because of reaching EOF).
*
*
- * Note that the implementation uses {@link #skip(Reader, long)}.
- * This means that the method may be considerably less efficient than using the actual skip implementation,
- * this is done to guarantee that the correct number of characters are skipped.
+ * Note that the implementation uses {@link #skip(Reader, long)}. This means that the method may be considerably less efficient than using the actual skip
+ * implementation, this is done to guarantee that the correct number of characters are skipped.
*
*
* @param reader stream to skip.
- * @param toSkip the number of characters to skip.
+ * @param toSkip The number of characters to skip.
* @throws IOException if there is a problem reading the file.
* @throws IllegalArgumentException if toSkip is negative.
* @throws EOFException if the number of characters skipped was incorrect.
@@ -2780,7 +2769,9 @@ public static void skipFully(final Reader reader, final long toSkip) throws IOEx
*
It has network timeout associated.
*
*
- * It can be used in favor of {@link #toByteArray(InputStream)}, since it avoids unnecessary allocation and copy of byte[].
+ * It can be used in favor of {@link #toByteArray(InputStream)}, since it avoids unnecessary allocation and copy of byte[].
+ *
+ *
* This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
- * It can be used in favor of {@link #toByteArray(InputStream)}, since it avoids unnecessary allocation and copy of byte[].
+ * It can be used in favor of {@link #toByteArray(InputStream)}, since it avoids unnecessary allocation and copy of byte[].
+ *
+ *
* This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
* @param input Stream to be fully buffered.
- * @param size the initial buffer size.
+ * @param size The initial buffer size.
* @return A fully buffered stream.
* @throws IOException if an I/O error occurs.
* @since 2.5
@@ -2819,11 +2812,10 @@ public static InputStream toBufferedInputStream(final InputStream input, final i
}
/**
- * Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given
- * reader.
+ * Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given reader.
*
- * @param reader the reader to wrap or return (not null).
- * @return the given reader or a new {@link BufferedReader} for the given reader.
+ * @param reader The reader to wrap or return (not null).
+ * @return The given reader or a new {@link BufferedReader} for the given reader.
* @throws NullPointerException if the input parameter is null.
* @see #buffer(Reader)
* @since 2.2
@@ -2833,12 +2825,11 @@ public static BufferedReader toBufferedReader(final Reader reader) {
}
/**
- * Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given
- * reader.
+ * Returns the given reader if it is a {@link BufferedReader}, otherwise creates a BufferedReader from the given reader.
*
- * @param reader the reader to wrap or return (not null).
- * @param size the buffer size, if a new BufferedReader is created.
- * @return the given reader or a new {@link BufferedReader} for the given reader.
+ * @param reader The reader to wrap or return (not null).
+ * @param size The buffer size, if a new BufferedReader is created.
+ * @return The given reader or a new {@link BufferedReader} for the given reader.
* @throws NullPointerException if the input parameter is null.
* @see #buffer(Reader)
* @since 2.5
@@ -2849,16 +2840,15 @@ public static BufferedReader toBufferedReader(final Reader reader, final int siz
/**
* Reads all the bytes from an input stream in a byte array.
- *
- *
The memory used by this method is proportional to the number
- * of bytes read, which is only limited by {@link Integer#MAX_VALUE}. Only streams
- * which fit into a single byte array with roughly 2 GiB limit can be processed
- * with this method.
+ *
+ * The memory used by this method is proportional to the number of bytes read, which is only limited by {@link Integer#MAX_VALUE}. Only
+ * streams which fit into a single byte array with roughly 2 GiB limit can be processed with this method.
+ *
*
* @param inputStream The {@link InputStream} to read; must not be {@code null}.
* @return A new byte array.
- * @throws IOException If an I/O error occurs while reading or if the maximum array size is exceeded.
- * @throws NullPointerException If {@code inputStream} is {@code null}.
+ * @throws IOException If an I/O error occurs while reading or if the maximum array size is exceeded.
+ * @throws NullPointerException If {@code inputStream} is {@code null}.
*/
public static byte[] toByteArray(final InputStream inputStream) throws IOException {
// Using SOFT_MAX_ARRAY_LENGTH guarantees that size() will not overflow
@@ -2871,14 +2861,14 @@ public static byte[] toByteArray(final InputStream inputStream) throws IOExcepti
/**
* Reads exactly {@code size} bytes from the given {@link InputStream} into a new {@code byte[]}.
+ *
+ * This variant always allocates the whole requested array size, for a dynamic growing variant use {@link #toByteArray(InputStream, int, int)}, which
+ * enforces stricter memory usage constraints.
+ *
*
- *
This variant always allocates the whole requested array size,
- * for a dynamic growing variant use {@link #toByteArray(InputStream, int, int)},
- * which enforces stricter memory usage constraints.
- *
- * @param input the {@link InputStream} to read; must not be {@code null}.
- * @param size the exact number of bytes to read; must be {@code >= 0}.
- * @return a new byte array of length {@code size}.
+ * @param input The {@link InputStream} to read; must not be {@code null}.
+ * @param size The exact number of bytes to read; must be {@code >= 0}.
+ * @return A new byte array of length {@code size}.
* @throws IllegalArgumentException if {@code size} is negative.
* @throws EOFException if the stream ends before {@code size} bytes are read.
* @throws IOException if an I/O error occurs while reading.
@@ -2891,20 +2881,18 @@ public static byte[] toByteArray(final InputStream input, final int size) throws
/**
* Reads exactly {@code size} bytes from the given {@link InputStream} into a new {@code byte[]}.
+ *
+ * The memory used by this method is proportional to the number of bytes read and limited by the specified {@code size}. This makes it
+ * suitable for processing large input streams, provided that sufficient heap space is available.
+ *
+ *
+ * This method processes the input stream in successive chunks of up to {@code chunkSize} bytes.
+ *
*
- *
The memory used by this method is proportional to the number
- * of bytes read and limited by the specified {@code size}. This makes it suitable for
- * processing large input streams, provided that sufficient heap space is
- * available.
- *
- *
This method processes the input stream in successive chunks of up to
- * {@code chunkSize} bytes.
- *
- * @param input the {@link InputStream} to read; must not be {@code null}.
- * @param size the exact number of bytes to read; must be {@code >= 0}.
- * The actual bytes read are validated to equal {@code size}.
- * @param chunkSize The chunk size for incremental reading; must be {@code > 0}.
- * @return a new byte array of length {@code size}.
+ * @param input The {@link InputStream} to read; must not be {@code null}.
+ * @param size The exact number of bytes to read; must be {@code >= 0}. The actual bytes read are validated to equal {@code size}.
+ * @param chunkSize The chunk size for incremental reading; must be {@code > 0}.
+ * @return A new byte array of length {@code size}.
* @throws IllegalArgumentException if {@code size} is negative or {@code chunkSize <= 0}.
* @throws EOFException if the stream ends before {@code size} bytes are read.
* @throws IOException if an I/O error occurs while reading.
@@ -2914,29 +2902,30 @@ public static byte[] toByteArray(final InputStream input, final int size) throws
public static byte[] toByteArray(final InputStream input, final int size, final int chunkSize) throws IOException {
Objects.requireNonNull(input, "input");
if (chunkSize <= 0) {
- throw new IllegalArgumentException("Chunk size must be greater than zero: " + chunkSize);
+ throw new IllegalArgumentException(String.format("chunkSize <= 0, chunkSize = %,d", chunkSize));
}
if (size <= chunkSize) {
// throws if size < 0
return toByteArray(input::read, size);
}
final UnsynchronizedByteArrayOutputStream output = copyToOutputStream(input, size, chunkSize);
- if (output.size() != size) {
- throw new EOFException("Unexpected read size, current: " + output.size() + ", expected: " + size);
+ final int outSize = output.size();
+ if (outSize != size) {
+ throw new EOFException(String.format("Expected read size: %,d, actual: %,d", size, outSize));
}
return output.toByteArray();
}
/**
* Reads exactly {@code size} bytes from the given {@link InputStream} into a new {@code byte[]}.
+ *
+ * This variant always allocates the whole requested array size, for a dynamic growing variant use {@link #toByteArray(InputStream, int, int)}, which
+ * enforces stricter memory usage constraints.
+ *
*
- *
This variant always allocates the whole requested array size,
- * for a dynamic growing variant use {@link #toByteArray(InputStream, int, int)},
- * which enforces stricter memory usage constraints.
- *
- * @param input the {@link InputStream} to read; must not be {@code null}.
- * @param size the exact number of bytes to read; must be {@code >= 0} and {@code <= Integer.MAX_VALUE}.
- * @return a new byte array of length {@code size}.
+ * @param input The {@link InputStream} to read; must not be {@code null}.
+ * @param size The exact number of bytes to read; must be {@code >= 0} and {@code <= Integer.MAX_VALUE}.
+ * @return A new byte array of length {@code size}.
* @throws IllegalArgumentException if {@code size} is negative or does not fit into an int.
* @throws EOFException if the stream ends before {@code size} bytes are read.
* @throws IOException if an I/O error occurs while reading.
@@ -2946,7 +2935,7 @@ public static byte[] toByteArray(final InputStream input, final int size, final
*/
public static byte[] toByteArray(final InputStream input, final long size) throws IOException {
if (size > Integer.MAX_VALUE) {
- throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size);
+ throw new IllegalArgumentException(String.format("size > Integer.MAX_VALUE, size = %,d", size));
}
return toByteArray(input, (int) size);
}
@@ -2954,15 +2943,16 @@ public static byte[] toByteArray(final InputStream input, final long size) throw
/**
* Gets the contents of an input as a {@code byte[]}.
*
- * @param input the input to read, not null.
- * @param size the size of the input to read, where 0 < {@code size} <= length of input.
+ * @param input The input to read, not null.
+ * @param size The size of the input to read, where 0 < {@code size} <= length of input.
* @return byte [] of length {@code size}.
- * @throws IOException if an I/O error occurs or input length is smaller than parameter {@code size}.
+ * @throws EOFException if the end of the input is reached before reading {@code size} bytes.
+ * @throws IOException if an I/O error occurs or input length is smaller than parameter {@code size}.
* @throws IllegalArgumentException if {@code size} is less than zero.
*/
static byte[] toByteArray(final IOTriFunction input, final int size) throws IOException {
if (size < 0) {
- throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
+ throw new IllegalArgumentException(String.format("size < 0, size = %,d", size));
}
if (size == 0) {
return EMPTY_BYTE_ARRAY;
@@ -2974,21 +2964,19 @@ static byte[] toByteArray(final IOTriFunction
offset += read;
}
if (offset != size) {
- throw new IOException("Unexpected read size, current: " + offset + ", expected: " + size);
+ throw new EOFException(String.format("Expected read size: %,d, actual: %,d", size, offset));
}
return data;
}
/**
- * Gets the contents of a {@link Reader} as a {@code byte[]}
- * using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Gets the contents of a {@link Reader} as a {@code byte[]} using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedReader}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
- * @param reader the {@link Reader} to read.
- * @return the requested byte array.
+ * @param reader The {@link Reader} to read.
+ * @return The requested byte array.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @deprecated Use {@link #toByteArray(Reader, Charset)} instead.
@@ -2999,16 +2987,14 @@ public static byte[] toByteArray(final Reader reader) throws IOException {
}
/**
- * Gets the contents of a {@link Reader} as a {@code byte[]}
- * using the specified character encoding.
+ * Gets the contents of a {@link Reader} as a {@code byte[]} using the specified character encoding.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedReader}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
- * @param reader the {@link Reader} to read.
- * @param charset the charset to use, null means platform default.
- * @return the requested byte array.
+ * @param reader The {@link Reader} to read.
+ * @param charset The charset to use, null means platform default.
+ * @return The requested byte array.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
@@ -3021,20 +3007,17 @@ public static byte[] toByteArray(final Reader reader, final Charset charset) thr
}
/**
- * Gets the contents of a {@link Reader} as a {@code byte[]}
- * using the specified character encoding.
+ * Gets the contents of a {@link Reader} as a {@code byte[]} using the specified character encoding.
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedReader}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
- * @param reader the {@link Reader} to read.
- * @param charsetName the name of the requested charset, null means platform default.
- * @return the requested byte array.
+ * @param reader The {@link Reader} to read.
+ * @param charsetName The name of the requested charset, null means platform default.
+ * @return The requested byte array.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
@@ -3045,14 +3028,13 @@ public static byte[] toByteArray(final Reader reader, final String charsetName)
}
/**
- * Gets the contents of a {@link String} as a {@code byte[]}
- * using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Gets the contents of a {@link String} as a {@code byte[]} using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
* This is the same as {@link String#getBytes()}.
*
*
- * @param input the {@link String} to convert.
- * @return the requested byte array.
+ * @param input The {@link String} to convert.
+ * @return The requested byte array.
* @throws NullPointerException if the input is null.
* @deprecated Use {@link String#getBytes()} instead.
*/
@@ -3065,8 +3047,8 @@ public static byte[] toByteArray(final String input) {
/**
* Gets the contents of a {@link URI} as a {@code byte[]}.
*
- * @param uri the {@link URI} to read.
- * @return the requested byte array.
+ * @param uri The {@link URI} to read.
+ * @return The requested byte array.
* @throws NullPointerException if the uri is null.
* @throws IOException if an I/O exception occurs.
* @since 2.4
@@ -3078,8 +3060,8 @@ public static byte[] toByteArray(final URI uri) throws IOException {
/**
* Gets the contents of a {@link URL} as a {@code byte[]}.
*
- * @param url the {@link URL} to read.
- * @return the requested byte array.
+ * @param url The {@link URL} to read.
+ * @return The requested byte array.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O exception occurs.
* @since 2.4
@@ -3093,10 +3075,10 @@ public static byte[] toByteArray(final URL url) throws IOException {
/**
* Gets the contents of a {@link URLConnection} as a {@code byte[]}.
*
- * @param urlConnection the {@link URLConnection} to read.
- * @return the requested byte array.
+ * @param urlConnection The {@link URLConnection} to read.
+ * @return The requested byte array.
* @throws NullPointerException if the urlConn is null.
- * @throws IOException if an I/O exception occurs.
+ * @throws IOException if an I/O exception occurs.
* @since 2.4
*/
public static byte[] toByteArray(final URLConnection urlConnection) throws IOException {
@@ -3106,19 +3088,17 @@ public static byte[] toByteArray(final URLConnection urlConnection) throws IOExc
}
/**
- * Gets the contents of an {@link InputStream} as a character array
- * using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Gets the contents of an {@link InputStream} as a character array using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param inputStream the {@link InputStream} to read.
- * @return the requested character array.
+ * @param inputStream The {@link InputStream} to read.
+ * @return The requested character array.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
- * @deprecated Use {@link #toCharArray(InputStream, Charset)} instead
+ * @deprecated Use {@link #toCharArray(InputStream, Charset)} instead.
*/
@Deprecated
public static char[] toCharArray(final InputStream inputStream) throws IOException {
@@ -3126,42 +3106,36 @@ public static char[] toCharArray(final InputStream inputStream) throws IOExcepti
}
/**
- * Gets the contents of an {@link InputStream} as a character array
- * using the specified character encoding.
+ * Gets the contents of an {@link InputStream} as a character array using the specified character encoding.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param inputStream the {@link InputStream} to read.
- * @param charset the charset to use, null means platform default.
- * @return the requested character array.
+ * @param inputStream The {@link InputStream} to read.
+ * @param charset The charset to use, null means platform default.
+ * @return The requested character array.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
*/
- public static char[] toCharArray(final InputStream inputStream, final Charset charset)
- throws IOException {
+ public static char[] toCharArray(final InputStream inputStream, final Charset charset) throws IOException {
final CharArrayWriter writer = new CharArrayWriter();
copy(inputStream, writer, charset);
return writer.toCharArray();
}
/**
- * Gets the contents of an {@link InputStream} as a character array
- * using the specified character encoding.
+ * Gets the contents of an {@link InputStream} as a character array using the specified character encoding.
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param inputStream the {@link InputStream} to read.
- * @param charsetName the name of the requested charset, null means platform default.
- * @return the requested character array.
+ * @param inputStream The {@link InputStream} to read.
+ * @param charsetName The name of the requested charset, null means platform default.
+ * @return The requested character array.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
@@ -3174,12 +3148,11 @@ public static char[] toCharArray(final InputStream inputStream, final String cha
/**
* Gets the contents of a {@link Reader} as a character array.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedReader}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
- * @param reader the {@link Reader} to read.
- * @return the requested character array.
+ * @param reader The {@link Reader} to read.
+ * @return The requested character array.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
@@ -3191,11 +3164,11 @@ public static char[] toCharArray(final Reader reader) throws IOException {
}
/**
- * Converts the specified CharSequence to an input stream, encoded as bytes
- * using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Converts the specified CharSequence to an input stream, encoded as bytes using the virtual machine's {@linkplain Charset#defaultCharset() default
+ * charset}.
*
- * @param input the CharSequence to convert.
- * @return an input stream.
+ * @param input The CharSequence to convert.
+ * @return An input stream.
* @since 2.0
* @deprecated Use {@link #toInputStream(CharSequence, Charset)} instead.
*/
@@ -3205,12 +3178,11 @@ public static InputStream toInputStream(final CharSequence input) {
}
/**
- * Converts the specified CharSequence to an input stream, encoded as bytes
- * using the specified character encoding.
+ * Converts the specified CharSequence to an input stream, encoded as bytes using the specified character encoding.
*
- * @param input the CharSequence to convert.
- * @param charset the charset to use, null means platform default.
- * @return an input stream.
+ * @param input The CharSequence to convert.
+ * @param charset The charset to use, null means platform default.
+ * @return An input stream.
* @since 2.3
*/
public static InputStream toInputStream(final CharSequence input, final Charset charset) {
@@ -3218,16 +3190,14 @@ public static InputStream toInputStream(final CharSequence input, final Charset
}
/**
- * Converts the specified CharSequence to an input stream, encoded as bytes
- * using the specified character encoding.
+ * Converts the specified CharSequence to an input stream, encoded as bytes using the specified character encoding.
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
- * @param input the CharSequence to convert.
- * @param charsetName the name of the requested charset, null means platform default.
- * @return an input stream.
+ * @param input The CharSequence to convert.
+ * @param charsetName The name of the requested charset, null means platform default.
+ * @return An input stream.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
* @since 2.0
*/
@@ -3236,11 +3206,10 @@ public static InputStream toInputStream(final CharSequence input, final String c
}
/**
- * Converts the specified string to an input stream, encoded as bytes
- * using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Converts the specified string to an input stream, encoded as bytes using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * @param input the string to convert.
- * @return an input stream.
+ * @param input The string to convert.
+ * @return An input stream.
* @since 1.1
* @deprecated Use {@link #toInputStream(String, Charset)} instead.
*/
@@ -3250,12 +3219,11 @@ public static InputStream toInputStream(final String input) {
}
/**
- * Converts the specified string to an input stream, encoded as bytes
- * using the specified character encoding.
+ * Converts the specified string to an input stream, encoded as bytes using the specified character encoding.
*
- * @param input the string to convert.
- * @param charset the charset to use, null means platform default.
- * @return an input stream.
+ * @param input The string to convert.
+ * @param charset The charset to use, null means platform default.
+ * @return An input stream.
* @since 2.3
*/
public static InputStream toInputStream(final String input, final Charset charset) {
@@ -3263,16 +3231,14 @@ public static InputStream toInputStream(final String input, final Charset charse
}
/**
- * Converts the specified string to an input stream, encoded as bytes
- * using the specified character encoding.
+ * Converts the specified string to an input stream, encoded as bytes using the specified character encoding.
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
- * @param input the string to convert.
- * @param charsetName the name of the requested charset, null means platform default.
- * @return an input stream.
+ * @param input The string to convert.
+ * @param charsetName The name of the requested charset, null means platform default.
+ * @return An input stream.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
* @since 1.1
*/
@@ -3281,11 +3247,10 @@ public static InputStream toInputStream(final String input, final String charset
}
/**
- * Gets the contents of a {@code byte[]} as a String
- * using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Gets the contents of a {@code byte[]} as a String using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * @param input the byte array to read.
- * @return the requested String.
+ * @param input The byte array to read.
+ * @return The requested String.
* @throws NullPointerException if the input is null.
* @deprecated Use {@link String#String(byte[])} instead.
*/
@@ -3296,16 +3261,14 @@ public static String toString(final byte[] input) {
}
/**
- * Gets the contents of a {@code byte[]} as a String
- * using the specified character encoding.
+ * Gets the contents of a {@code byte[]} as a String using the specified character encoding.
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
- * @param input the byte array to read.
- * @param charsetName the name of the requested charset, null means platform default.
- * @return the requested String.
+ * @param input The byte array to read.
+ * @param charsetName The name of the requested charset, null means platform default.
+ * @return The requested String.
* @throws NullPointerException if the input is null.
*/
public static String toString(final byte[] input, final String charsetName) {
@@ -3313,15 +3276,13 @@ public static String toString(final byte[] input, final String charsetName) {
}
/**
- * Gets the contents of an {@link InputStream} as a String
- * using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Gets the contents of an {@link InputStream} as a String using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param input the {@link InputStream} to read.
- * @return the requested String.
+ * @param input The {@link InputStream} to read.
+ * @return The requested String.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @deprecated Use {@link #toString(InputStream, Charset)} instead.
@@ -3332,16 +3293,14 @@ public static String toString(final InputStream input) throws IOException {
}
/**
- * Gets the contents of an {@link InputStream} as a String
- * using the specified character encoding.
+ * Gets the contents of an {@link InputStream} as a String using the specified character encoding.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param input the {@link InputStream} to read.
- * @param charset the charset to use, null means platform default.
- * @return the requested String.
+ * @param input The {@link InputStream} to read.
+ * @param charset The charset to use, null means platform default.
+ * @return The requested String.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
@@ -3354,40 +3313,34 @@ public static String toString(final InputStream input, final Charset charset) th
}
/**
- * Gets the contents of an {@link InputStream} as a String
- * using the specified character encoding.
+ * Gets the contents of an {@link InputStream} as a String using the specified character encoding.
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param input the {@link InputStream} to read.
- * @param charsetName the name of the requested charset, null means platform default.
- * @return the requested String.
+ * @param input The {@link InputStream} to read.
+ * @param charsetName The name of the requested charset, null means platform default.
+ * @return The requested String.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
*/
- public static String toString(final InputStream input, final String charsetName)
- throws IOException {
+ public static String toString(final InputStream input, final String charsetName) throws IOException {
return toString(input, Charsets.toCharset(charsetName));
}
/**
- * Gets the contents of an {@link InputStream} from a supplier as a String
- * using the specified character encoding.
+ * Gets the contents of an {@link InputStream} from a supplier as a String using the specified character encoding.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param input supplies the {@link InputStream} to read.
- * @param charset the charset to use, null means platform default.
- * @return the requested String.
+ * @param input supplies the {@link InputStream} to read.
+ * @param charset The charset to use, null means platform default.
+ * @return The requested String.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @since 2.12.0
@@ -3399,17 +3352,15 @@ public static String toString(final IOSupplier input, final Charset
}
/**
- * Gets the contents of an {@link InputStream} from a supplier as a String
- * using the specified character encoding.
+ * Gets the contents of an {@link InputStream} from a supplier as a String using the specified character encoding.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedInputStream}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedInputStream}.
*
*
- * @param input supplies the {@link InputStream} to read.
- * @param charset the charset to use, null means platform default.
- * @param defaultString the default return value if the supplier or its value is null.
- * @return the requested String.
+ * @param input supplies the {@link InputStream} to read.
+ * @param charset The charset to use, null means platform default.
+ * @param defaultString The default return value if the supplier or its value is null.
+ * @return The requested String.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @since 2.12.0
@@ -3426,12 +3377,11 @@ public static String toString(final IOSupplier input, final Charset
/**
* Gets the contents of a {@link Reader} as a String.
*
- * This method buffers the input internally, so there is no need to use a
- * {@link BufferedReader}.
+ * This method buffers the input internally, so there is no need to use a {@link BufferedReader}.
*
*
- * @param reader the {@link Reader} to read.
- * @return the requested String.
+ * @param reader The {@link Reader} to read.
+ * @return The requested String.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
*/
@@ -3443,7 +3393,7 @@ public static String toString(final Reader reader) throws IOException {
}
/**
- * Gets the contents at the given URI using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Gets the contents at the given URI using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
* @param uri The URI source.
* @return The contents of the URL as a String.
@@ -3459,7 +3409,7 @@ public static String toString(final URI uri) throws IOException {
/**
* Gets the contents at the given URI.
*
- * @param uri The URI source.
+ * @param uri The URI source.
* @param encoding The encoding name for the URL contents.
* @return The contents of the URL as a String.
* @throws IOException if an I/O exception occurs.
@@ -3472,7 +3422,7 @@ public static String toString(final URI uri, final Charset encoding) throws IOEx
/**
* Gets the contents at the given URI.
*
- * @param uri The URI source.
+ * @param uri The URI source.
* @param charsetName The encoding name for the URL contents.
* @return The contents of the URL as a String.
* @throws IOException if an I/O exception occurs.
@@ -3484,7 +3434,7 @@ public static String toString(final URI uri, final String charsetName) throws IO
}
/**
- * Gets the contents at the given URL using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Gets the contents at the given URL using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
* @param url The URL source.
* @return The contents of the URL as a String.
@@ -3500,7 +3450,7 @@ public static String toString(final URL url) throws IOException {
/**
* Gets the contents at the given URL.
*
- * @param url The URL source.
+ * @param url The URL source.
* @param encoding The encoding name for the URL contents.
* @return The contents of the URL as a String.
* @throws IOException if an I/O exception occurs.
@@ -3513,7 +3463,7 @@ public static String toString(final URL url, final Charset encoding) throws IOEx
/**
* Gets the contents at the given URL.
*
- * @param url The URL source.
+ * @param url The URL source.
* @param charsetName The encoding name for the URL contents.
* @return The contents of the URL as a String.
* @throws IOException if an I/O exception occurs.
@@ -3527,29 +3477,26 @@ public static String toString(final URL url, final String charsetName) throws IO
/**
* Writes bytes from a {@code byte[]} to an {@link OutputStream}.
*
- * @param data the byte array to write, do not modify during output, null ignored.
- * @param output the {@link OutputStream} to write to.
+ * @param data The byte array to write, do not modify during output, null ignored.
+ * @param output The {@link OutputStream} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
*/
- public static void write(final byte[] data, final OutputStream output)
- throws IOException {
+ public static void write(final byte[] data, final OutputStream output) throws IOException {
if (data != null) {
output.write(data);
}
}
/**
- * Writes bytes from a {@code byte[]} to chars on a {@link Writer}
- * using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Writes bytes from a {@code byte[]} to chars on a {@link Writer} using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
* This method uses {@link String#String(byte[])}.
*
*
- * @param data the byte array to write, do not modify during output,
- * null ignored
- * @param writer the {@link Writer} to write to.
+ * @param data The byte array to write, do not modify during output, null ignored.
+ * @param writer The {@link Writer} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
@@ -3561,16 +3508,14 @@ public static void write(final byte[] data, final Writer writer) throws IOExcept
}
/**
- * Writes bytes from a {@code byte[]} to chars on a {@link Writer}
- * using the specified character encoding.
+ * Writes bytes from a {@code byte[]} to chars on a {@link Writer} using the specified character encoding.
*
* This method uses {@link String#String(byte[], String)}.
*
*
- * @param data the byte array to write, do not modify during output,
- * null ignored
- * @param writer the {@link Writer} to write to.
- * @param charset the charset to use, null means platform default.
+ * @param data The byte array to write, do not modify during output, null ignored.
+ * @param writer The {@link Writer} to write to.
+ * @param charset The charset to use, null means platform default.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
@@ -3584,15 +3529,15 @@ public static void write(final byte[] data, final Writer writer, final Charset c
/**
* Writes bytes from a {@code byte[]} to chars on a {@link Writer} using the specified character encoding.
*
- * Character encoding names can be found at IANA.
+ * Character encoding names can be found at IANA.
*
*
* This method uses {@link String#String(byte[], String)}.
*
*
- * @param data the byte array to write, do not modify during output, null ignored.
- * @param writer the {@link Writer} to write to.
- * @param charsetName the name of the requested charset, null means platform default.
+ * @param data The byte array to write, do not modify during output, null ignored.
+ * @param writer The {@link Writer} to write to.
+ * @param charsetName The name of the requested charset, null means platform default.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
@@ -3605,19 +3550,18 @@ public static void write(final byte[] data, final Writer writer, final String ch
/**
* Writes chars from a {@code char[]} to bytes on an {@link OutputStream}.
*
- * This method uses the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * This method uses the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
*
- * @param data the char array to write, do not modify during output, null ignored.
- * @param output the {@link OutputStream} to write to.
+ * @param data The char array to write, do not modify during output, null ignored.
+ * @param output The {@link OutputStream} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
* @deprecated Use {@link #write(char[], OutputStream, Charset)} instead.
*/
@Deprecated
- public static void write(final char[] data, final OutputStream output)
- throws IOException {
+ public static void write(final char[] data, final OutputStream output) throws IOException {
write(data, output, Charset.defaultCharset());
}
@@ -3627,9 +3571,9 @@ public static void write(final char[] data, final OutputStream output)
* This method uses {@link String#String(char[])} and {@link String#getBytes(String)}.
*
*
- * @param data the char array to write, do not modify during output, null ignored.
- * @param output the {@link OutputStream} to write to.
- * @param charset the charset to use, null means platform default.
+ * @param data The char array to write, do not modify during output, null ignored.
+ * @param output The {@link OutputStream} to write to.
+ * @param charset The charset to use, null means platform default.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
@@ -3643,30 +3587,29 @@ public static void write(final char[] data, final OutputStream output, final Cha
/**
* Writes chars from a {@code char[]} to bytes on an {@link OutputStream} using the specified character encoding.
*
- * Character encoding names can be found at IANA.
+ * Character encoding names can be found at IANA.
*
*
* This method uses {@link String#String(char[])} and {@link String#getBytes(String)}.
*
*
- * @param data the char array to write, do not modify during output, null ignored.
- * @param output the {@link OutputStream} to write to.
- * @param charsetName the name of the requested charset, null means platform default.
+ * @param data The char array to write, do not modify during output, null ignored.
+ * @param output The {@link OutputStream} to write to.
+ * @param charsetName The name of the requested charset, null means platform default.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
* @since 1.1
*/
- public static void write(final char[] data, final OutputStream output, final String charsetName)
- throws IOException {
+ public static void write(final char[] data, final OutputStream output, final String charsetName) throws IOException {
write(data, output, Charsets.toCharset(charsetName));
}
/**
* Writes chars from a {@code char[]} to a {@link Writer}
*
- * @param data the char array to write, do not modify during output, null ignored.
- * @param writer the {@link Writer} to write to.
+ * @param data The char array to write, do not modify during output, null ignored.
+ * @param writer The {@link Writer} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
@@ -3684,16 +3627,15 @@ public static void write(final char[] data, final Writer writer) throws IOExcept
* This method uses {@link String#getBytes()}.
*
*
- * @param data the {@link CharSequence} to write, null ignored.
- * @param output the {@link OutputStream} to write to.
+ * @param data The {@link CharSequence} to write, null ignored.
+ * @param output The {@link OutputStream} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 2.0
* @deprecated Use {@link #write(CharSequence, OutputStream, Charset)} instead.
*/
@Deprecated
- public static void write(final CharSequence data, final OutputStream output)
- throws IOException {
+ public static void write(final CharSequence data, final OutputStream output) throws IOException {
write(data, output, Charset.defaultCharset());
}
@@ -3703,15 +3645,14 @@ public static void write(final CharSequence data, final OutputStream output)
* This method uses {@link String#getBytes(String)}.
*
*
- * @param data the {@link CharSequence} to write, null ignored.
- * @param output the {@link OutputStream} to write to.
- * @param charset the charset to use, null means platform default.
+ * @param data The {@link CharSequence} to write, null ignored.
+ * @param output The {@link OutputStream} to write to.
+ * @param charset The charset to use, null means platform default.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
*/
- public static void write(final CharSequence data, final OutputStream output, final Charset charset)
- throws IOException {
+ public static void write(final CharSequence data, final OutputStream output, final Charset charset) throws IOException {
if (data != null) {
write(data.toString(), output, charset);
}
@@ -3720,30 +3661,29 @@ public static void write(final CharSequence data, final OutputStream output, fin
/**
* Writes chars from a {@link CharSequence} to bytes on an {@link OutputStream} using the specified character encoding.
*
- * Character encoding names can be found at IANA.
+ * Character encoding names can be found at IANA.
*
*
* This method uses {@link String#getBytes(String)}.
*
*
- * @param data the {@link CharSequence} to write, null ignored.
- * @param output the {@link OutputStream} to write to.
- * @param charsetName the name of the requested charset, null means platform default.
+ * @param data The {@link CharSequence} to write, null ignored.
+ * @param output The {@link OutputStream} to write to.
+ * @param charsetName The name of the requested charset, null means platform default.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
* @since 2.0
*/
- public static void write(final CharSequence data, final OutputStream output, final String charsetName)
- throws IOException {
+ public static void write(final CharSequence data, final OutputStream output, final String charsetName) throws IOException {
write(data, output, Charsets.toCharset(charsetName));
}
/**
* Writes chars from a {@link CharSequence} to a {@link Writer}.
*
- * @param data the {@link CharSequence} to write, null ignored.
- * @param writer the {@link Writer} to write to.
+ * @param data The {@link CharSequence} to write, null ignored.
+ * @param writer The {@link Writer} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 2.0
@@ -3755,35 +3695,32 @@ public static void write(final CharSequence data, final Writer writer) throws IO
}
/**
- * Writes chars from a {@link String} to bytes on an
- * {@link OutputStream} using the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * Writes chars from a {@link String} to bytes on an {@link OutputStream} using the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
* This method uses {@link String#getBytes()}.
*
*
- * @param data the {@link String} to write, null ignored.
- * @param output the {@link OutputStream} to write to.
+ * @param data The {@link String} to write, null ignored.
+ * @param output The {@link OutputStream} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
- * @deprecated Use {@link #write(String, OutputStream, Charset)} instead
+ * @deprecated Use {@link #write(String, OutputStream, Charset)} instead.
*/
@Deprecated
- public static void write(final String data, final OutputStream output)
- throws IOException {
+ public static void write(final String data, final OutputStream output) throws IOException {
write(data, output, Charset.defaultCharset());
}
/**
- * Writes chars from a {@link String} to bytes on an
- * {@link OutputStream} using the specified character encoding.
+ * Writes chars from a {@link String} to bytes on an {@link OutputStream} using the specified character encoding.
*
* This method uses {@link String#getBytes(String)}.
*
*
- * @param data the {@link String} to write, null ignored.
- * @param output the {@link OutputStream} to write to.
- * @param charset the charset to use, null means platform default.
+ * @param data The {@link String} to write, null ignored.
+ * @param output The {@link OutputStream} to write to.
+ * @param charset The charset to use, null means platform default.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
@@ -3799,34 +3736,31 @@ public static void write(final String data, final OutputStream output, final Cha
}
/**
- * Writes chars from a {@link String} to bytes on an
- * {@link OutputStream} using the specified character encoding.
+ * Writes chars from a {@link String} to bytes on an {@link OutputStream} using the specified character encoding.
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
* This method uses {@link String#getBytes(String)}.
*
*
- * @param data the {@link String} to write, null ignored.
- * @param output the {@link OutputStream} to write to.
- * @param charsetName the name of the requested charset, null means platform default.
- * @throws NullPointerException if output is null.
- * @throws IOException if an I/O error occurs.
+ * @param data The {@link String} to write, null ignored.
+ * @param output The {@link OutputStream} to write to.
+ * @param charsetName The name of the requested charset, null means platform default.
+ * @throws NullPointerException if output is null.
+ * @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
* @since 1.1
*/
- public static void write(final String data, final OutputStream output, final String charsetName)
- throws IOException {
+ public static void write(final String data, final OutputStream output, final String charsetName) throws IOException {
write(data, output, Charsets.toCharset(charsetName));
}
/**
* Writes chars from a {@link String} to a {@link Writer}.
*
- * @param data the {@link String} to write, null ignored.
- * @param writer the {@link Writer} to write to.
+ * @param data The {@link String} to write, null ignored.
+ * @param writer The {@link Writer} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
@@ -3838,49 +3772,45 @@ public static void write(final String data, final Writer writer) throws IOExcept
}
/**
- * Writes chars from a {@link StringBuffer} to bytes on an
- * {@link OutputStream} using the default character encoding of the
- * platform.
+ * Writes chars from a {@link StringBuffer} to bytes on an {@link OutputStream} using the default character encoding of the platform.
*
* This method uses {@link String#getBytes()}.
*
*
- * @param data the {@link StringBuffer} to write, null ignored.
- * @param output the {@link OutputStream} to write to.
+ * @param data The {@link StringBuffer} to write, null ignored.
+ * @param output The {@link OutputStream} to write to.
* @throws NullPointerException if output is null.
- * @throws IOException if an I/O error occurs
+ * @throws IOException if an I/O error occurs.
* @since 1.1
* @deprecated Use {@link #write(CharSequence, OutputStream)}.
*/
@Deprecated
- public static void write(final StringBuffer data, final OutputStream output) //NOSONAR
+ public static void write(final StringBuffer data, final OutputStream output) // NOSONAR
throws IOException {
write(data, output, (String) null);
}
/**
- * Writes chars from a {@link StringBuffer} to bytes on an
- * {@link OutputStream} using the specified character encoding.
+ * Writes chars from a {@link StringBuffer} to bytes on an {@link OutputStream} using the specified character encoding.
*
- * Character encoding names can be found at
- * IANA.
+ * Character encoding names can be found at IANA.
*
*
* This method uses {@link String#getBytes(String)}.
*
*
- * @param data the {@link StringBuffer} to write, null ignored.
- * @param output the {@link OutputStream} to write to.
- * @param charsetName the name of the requested charset, null means platform default.
- * @throws NullPointerException if output is null.
- * @throws IOException if an I/O error occurs.
+ * @param data The {@link StringBuffer} to write, null ignored.
+ * @param output The {@link OutputStream} to write to.
+ * @param charsetName The name of the requested charset, null means platform default.
+ * @throws NullPointerException if output is null.
+ * @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
* @since 1.1
* @deprecated Use {@link #write(CharSequence, OutputStream, String)}.
*/
@Deprecated
- public static void write(final StringBuffer data, final OutputStream output, final String charsetName) //NOSONAR
- throws IOException {
+ public static void write(final StringBuffer data, final OutputStream output, final String charsetName) // NOSONAR
+ throws IOException {
if (data != null) {
write(data.toString(), output, Charsets.toCharset(charsetName));
}
@@ -3889,15 +3819,15 @@ public static void write(final StringBuffer data, final OutputStream output, fin
/**
* Writes chars from a {@link StringBuffer} to a {@link Writer}.
*
- * @param data the {@link StringBuffer} to write, null ignored.
- * @param writer the {@link Writer} to write to.
+ * @param data The {@link StringBuffer} to write, null ignored.
+ * @param writer The {@link Writer} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
* @deprecated Use {@link #write(CharSequence, Writer)}.
*/
@Deprecated
- public static void write(final StringBuffer data, final Writer writer) //NOSONAR
+ public static void write(final StringBuffer data, final Writer writer) // NOSONAR
throws IOException {
if (data != null) {
writer.write(data.toString());
@@ -3905,19 +3835,16 @@ public static void write(final StringBuffer data, final Writer writer) //NOSONAR
}
/**
- * Writes bytes from a {@code byte[]} to an {@link OutputStream} using chunked writes.
- * This is intended for writing very large byte arrays which might otherwise cause excessive
- * memory usage if the native code has to allocate a copy.
+ * Writes bytes from a {@code byte[]} to an {@link OutputStream} using chunked writes. This is intended for writing very large byte arrays which might
+ * otherwise cause excessive memory usage if the native code has to allocate a copy.
*
- * @param data the byte array to write, do not modify during output,
- * null ignored.
- * @param output the {@link OutputStream} to write to.
+ * @param data The byte array to write, do not modify during output, null ignored.
+ * @param output The {@link OutputStream} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 2.5
*/
- public static void writeChunked(final byte[] data, final OutputStream output)
- throws IOException {
+ public static void writeChunked(final byte[] data, final OutputStream output) throws IOException {
if (data != null) {
int bytes = data.length;
int offset = 0;
@@ -3934,8 +3861,8 @@ public static void writeChunked(final byte[] data, final OutputStream output)
* Writes chars from a {@code char[]} to a {@link Writer} using chunked writes. This is intended for writing very large byte arrays which might otherwise
* cause excessive memory usage if the native code has to allocate a copy.
*
- * @param data the char array to write, do not modify during output, null ignored.
- * @param writer the {@link Writer} to write to.
+ * @param data The char array to write, do not modify during output, null ignored.
+ * @param writer The {@link Writer} to write to.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 2.5
@@ -3955,15 +3882,15 @@ public static void writeChunked(final char[] data, final Writer writer) throws I
/**
* Writes the {@link #toString()} value of each item in a collection to an {@link OutputStream} line by line, using the virtual machine's
- * {@link Charset#defaultCharset() default charset} and the specified line ending.
+ * {@linkplain Charset#defaultCharset() default charset} and the specified line ending.
*
- * @param lines the lines to write, null entries produce blank lines.
- * @param lineEnding the line separator to use, null is system default.
- * @param output the {@link OutputStream} to write to, not null, not closed.
+ * @param lines The lines to write, null entries produce blank lines.
+ * @param lineEnding The line separator to use, null is system default.
+ * @param output The {@link OutputStream} to write to, not null, not closed.
* @throws NullPointerException if the output is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
- * @deprecated Use {@link #writeLines(Collection, String, OutputStream, Charset)} instead
+ * @deprecated Use {@link #writeLines(Collection, String, OutputStream, Charset)} instead.
*/
@Deprecated
public static void writeLines(final Collection> lines, final String lineEnding, final OutputStream output) throws IOException {
@@ -3977,10 +3904,10 @@ public static void writeLines(final Collection> lines, final String lineEnding
* UTF-16 is written big-endian with no byte order mark. For little-endian, use UTF-16LE. For a BOM, write it to the stream before calling this method.
*
*
- * @param lines the lines to write, null entries produce blank lines.
- * @param lineEnding the line separator to use, null is system default.
- * @param output the {@link OutputStream} to write to, not null, not closed.
- * @param charset the charset to use, null means platform default.
+ * @param lines The lines to write, null entries produce blank lines.
+ * @param lineEnding The line separator to use, null is system default.
+ * @param output The {@link OutputStream} to write to, not null, not closed.
+ * @param charset The charset to use, null means platform default.
* @throws NullPointerException if output is null.
* @throws IOException if an I/O error occurs.
* @since 2.3
@@ -4009,13 +3936,13 @@ public static void writeLines(final Collection> lines, String lineEnding, fina
* Writes the {@link #toString()} value of each item in a collection to an {@link OutputStream} line by line, using the specified character encoding and the
* specified line ending.
*
- * Character encoding names can be found at IANA.
+ * Character encoding names can be found at IANA.
*
*
- * @param lines the lines to write, null entries produce blank lines.
- * @param lineEnding the line separator to use, null is system default.
- * @param output the {@link OutputStream} to write to, not null, not closed.
- * @param charsetName the name of the requested charset, null means platform default.
+ * @param lines The lines to write, null entries produce blank lines.
+ * @param lineEnding The line separator to use, null is system default.
+ * @param output The {@link OutputStream} to write to, not null, not closed.
+ * @param charsetName The name of the requested charset, null means platform default.
* @throws NullPointerException if the output is null.
* @throws IOException if an I/O error occurs.
* @throws java.nio.charset.UnsupportedCharsetException if the encoding is not supported.
@@ -4028,9 +3955,9 @@ public static void writeLines(final Collection> lines, final String lineEnding
/**
* Writes the {@link #toString()} value of each item in a collection to a {@link Writer} line by line, using the specified line ending.
*
- * @param lines the lines to write, null entries produce blank lines.
- * @param lineEnding the line separator to use, null is system default.
- * @param writer the {@link Writer} to write to, not null, not closed.
+ * @param lines The lines to write, null entries produce blank lines.
+ * @param lineEnding The line separator to use, null is system default.
+ * @param writer The {@link Writer} to write to, not null, not closed.
* @throws NullPointerException if the input is null.
* @throws IOException if an I/O error occurs.
* @since 1.1
@@ -4051,11 +3978,10 @@ public static void writeLines(final Collection> lines, String lineEnding, fina
}
/**
- * Returns the given Appendable if it is already a {@link Writer}, otherwise creates a Writer wrapper around the
- * given Appendable.
+ * Returns the given Appendable if it is already a {@link Writer}, otherwise creates a Writer wrapper around the given Appendable.
*
- * @param appendable the Appendable to wrap or return (not null).
- * @return the given Appendable or a Writer wrapper around the given Appendable.
+ * @param appendable The Appendable to wrap or return (not null).
+ * @return The given Appendable or a Writer wrapper around the given Appendable.
* @throws NullPointerException if the input parameter is null.
* @since 2.7
*/
@@ -4076,8 +4002,7 @@ public static Writer writer(final Appendable appendable) {
* @deprecated TODO Make private in 3.0.
*/
@Deprecated
- public IOUtils() { //NOSONAR
+ public IOUtils() { // NOSONAR
// empty
}
-
}
diff --git a/src/main/java/org/apache/commons/io/LineIterator.java b/src/main/java/org/apache/commons/io/LineIterator.java
index 293847e7a72..3ce87b39a2f 100644
--- a/src/main/java/org/apache/commons/io/LineIterator.java
+++ b/src/main/java/org/apache/commons/io/LineIterator.java
@@ -56,9 +56,9 @@ public class LineIterator implements Iterator, Closeable {
* Closes a {@link LineIterator} quietly.
*
* @param iterator The iterator to close, or {@code null}.
+ * @see Throwable#addSuppressed(Throwable)
* @deprecated As of 2.6 deprecated without replacement. Please use the try-with-resources statement or handle
* suppressed exceptions manually.
- * @see Throwable#addSuppressed(Throwable)
*/
@Deprecated
public static void closeQuietly(final LineIterator iterator) {
@@ -77,17 +77,12 @@ public static void closeQuietly(final LineIterator iterator) {
/**
* Constructs an iterator of the lines for a {@link Reader}.
*
- * @param reader the {@link Reader} to read from, not null
- * @throws NullPointerException if the reader is null
+ * @param reader The {@link Reader} to read from, not null.
+ * @throws NullPointerException if the reader is null.
*/
@SuppressWarnings("resource") // Caller closes Reader
public LineIterator(final Reader reader) {
- Objects.requireNonNull(reader, "reader");
- if (reader instanceof BufferedReader) {
- bufferedReader = (BufferedReader) reader;
- } else {
- bufferedReader = new BufferedReader(reader);
- }
+ bufferedReader = IOUtils.buffer(Objects.requireNonNull(reader, "reader"));
}
/**
@@ -111,8 +106,8 @@ public void close() throws IOException {
* If there is an {@link IOException} then {@link #close()} will
* be called on this instance.
*
- * @return {@code true} if the Reader has more lines
- * @throws IllegalStateException if an IO exception occurs
+ * @return {@code true} if the Reader has more lines.
+ * @throws IllegalStateException if an IO exception occurs.
*/
@Override
public boolean hasNext() {
@@ -135,16 +130,16 @@ public boolean hasNext() {
}
}
} catch (final IOException ioe) {
- IOUtils.closeQuietly(this, ioe::addSuppressed);
- throw new IllegalStateException(ioe);
+ throw new IllegalStateException(IOUtils.closeQuietlySuppress(this, ioe));
}
}
/**
* Overridable method to validate each line that is returned.
* This implementation always returns true.
- * @param line the line that is to be validated
- * @return true if valid, false to remove from the iterator
+ *
+ * @param line The line that is to be validated.
+ * @return true if valid, false to remove from the iterator.
*/
protected boolean isValidLine(final String line) {
return true;
@@ -153,8 +148,8 @@ protected boolean isValidLine(final String line) {
/**
* Returns the next line in the wrapped {@link Reader}.
*
- * @return the next line from the input
- * @throws NoSuchElementException if there is no line to return
+ * @return The next line from the input.
+ * @throws NoSuchElementException if there is no line to return.
*/
@Override
public String next() {
@@ -164,8 +159,8 @@ public String next() {
/**
* Returns the next line in the wrapped {@link Reader}.
*
- * @return the next line from the input
- * @throws NoSuchElementException if there is no line to return
+ * @return The next line from the input.
+ * @throws NoSuchElementException if there is no line to return.
* @deprecated Use {@link #next()}.
*/
@Deprecated
@@ -181,7 +176,7 @@ public String nextLine() {
/**
* Unsupported.
*
- * @throws UnsupportedOperationException always
+ * @throws UnsupportedOperationException always.
*/
@Override
public void remove() {
diff --git a/src/main/java/org/apache/commons/io/RandomAccessFileMode.java b/src/main/java/org/apache/commons/io/RandomAccessFileMode.java
index 88f499d120b..17bd80911ab 100644
--- a/src/main/java/org/apache/commons/io/RandomAccessFileMode.java
+++ b/src/main/java/org/apache/commons/io/RandomAccessFileMode.java
@@ -157,14 +157,14 @@ public static RandomAccessFileMode valueOfMode(final String mode) {
* This method allocates and releases the {@link RandomAccessFile} given to the consumer.
*
*
- * @param file the file specifying the {@link RandomAccessFile} to open.
- * @param consumer the function to apply.
+ * @param file The file specifying the {@link RandomAccessFile} to open.
+ * @param consumer The function to apply.
* @throws FileNotFoundException See {@link IORandomAccessFile#IORandomAccessFile(File, String)}.
* @throws IOException Thrown by the given function.
* @since 2.18.0
*/
- public void accept(final Path file, final IOConsumer consumer) throws IOException {
- try (RandomAccessFile raf = create(file)) {
+ public void accept(final Path file, final IOConsumer consumer) throws IOException {
+ try (IORandomAccessFile raf = new IORandomAccessFile(file.toFile(), mode)) {
consumer.accept(raf);
}
}
@@ -175,10 +175,10 @@ public void accept(final Path file, final IOConsumer consumer)
* This method allocates and releases the {@link RandomAccessFile} given to the function.
*
*
- * @param the return type of the function.
- * @param file the file specifying the {@link RandomAccessFile} to open.
- * @param function the function to apply.
- * @return the function's result value.
+ * @param The return type of the function.
+ * @param file The file specifying the {@link RandomAccessFile} to open.
+ * @param function The function to apply.
+ * @return The function's result value.
* @throws FileNotFoundException See {@link IORandomAccessFile#IORandomAccessFile(File, String)}.
* @throws IOException Thrown by the given function.
* @since 2.18.0
@@ -195,8 +195,8 @@ public T apply(final Path file, final IOFunction functi
* Prefer {@link #create(Path)} over this.
*
*
- * @param file the file object
- * @return a random access file
+ * @param file The file object.
+ * @return A random access file.
* @throws FileNotFoundException See {@link IORandomAccessFile#IORandomAccessFile(File, String)}.
*/
public RandomAccessFile create(final File file) throws FileNotFoundException {
@@ -206,8 +206,8 @@ public RandomAccessFile create(final File file) throws FileNotFoundException {
/**
* Constructs a random access file to read from, and optionally to write to, the file specified by the {@link File} argument.
*
- * @param file the file object
- * @return a random access file
+ * @param file The file object.
+ * @return A random access file.
* @throws FileNotFoundException See {@link IORandomAccessFile#IORandomAccessFile(File, String)}.
*/
public RandomAccessFile create(final Path file) throws FileNotFoundException {
@@ -220,8 +220,8 @@ public RandomAccessFile create(final Path file) throws FileNotFoundException {
* Prefer {@link #create(Path)} over this.
*
*
- * @param name the file object
- * @return a random access file
+ * @param name The file object.
+ * @return A random access file.
* @throws FileNotFoundException See {@link IORandomAccessFile#IORandomAccessFile(File, String)}.
*/
public RandomAccessFile create(final String name) throws FileNotFoundException {
@@ -270,7 +270,7 @@ public String getMode() {
*
*
*
- * @param other the non-null mode to test against.
+ * @param other The non-null mode to test against.
* @return whether this mode implies the given {@code other} mode.
* @since 2.18.0
*/
@@ -282,8 +282,8 @@ public boolean implies(final RandomAccessFileMode other) {
/**
* Constructs a random access file to read from, and optionally to write to, the file specified by the {@link File} argument.
*
- * @param name the file object
- * @return a random access file
+ * @param name The system-dependent file name.
+ * @return A random access file.
* @throws FileNotFoundException See {@link IORandomAccessFile#IORandomAccessFile(File, String)}.
* @since 2.18.0
*/
diff --git a/src/main/java/org/apache/commons/io/RandomAccessFiles.java b/src/main/java/org/apache/commons/io/RandomAccessFiles.java
index 46de0dbf077..4f47536f4ae 100644
--- a/src/main/java/org/apache/commons/io/RandomAccessFiles.java
+++ b/src/main/java/org/apache/commons/io/RandomAccessFiles.java
@@ -71,7 +71,7 @@ private static long length(final RandomAccessFile raf) throws IOException {
* @param input The source RandomAccessFile.
* @param position The offset position, measured in bytes from the beginning of the file, at which to set the file pointer.
* @param length How many bytes to read.
- * @return a new byte array.
+ * @return A new byte array.
* @throws IOException If the first byte cannot be read for any reason other than end of file, or if the random access file has been closed, or if some
* other I/O error occurs.
*/
diff --git a/src/main/java/org/apache/commons/io/StandardLineSeparator.java b/src/main/java/org/apache/commons/io/StandardLineSeparator.java
index 3a030da2eda..2424aa3f254 100644
--- a/src/main/java/org/apache/commons/io/StandardLineSeparator.java
+++ b/src/main/java/org/apache/commons/io/StandardLineSeparator.java
@@ -47,7 +47,7 @@ public enum StandardLineSeparator {
/**
* Constructs a new instance for a non-null line separator.
*
- * @param lineSeparator a non-null line separator.
+ * @param lineSeparator A non-null line separator.
*/
StandardLineSeparator(final String lineSeparator) {
this.lineSeparator = Objects.requireNonNull(lineSeparator, "lineSeparator");
@@ -56,8 +56,8 @@ public enum StandardLineSeparator {
/**
* Gets the bytes for this instance encoded using the given Charset.
*
- * @param charset the encoding Charset.
- * @return the bytes for this instance encoded using the given Charset.
+ * @param charset The encoding Charset.
+ * @return The bytes for this instance encoded using the given Charset.
*/
public byte[] getBytes(final Charset charset) {
return lineSeparator.getBytes(charset);
@@ -66,7 +66,7 @@ public byte[] getBytes(final Charset charset) {
/**
* Gets the String value of this instance.
*
- * @return the String value of this instance.
+ * @return The String value of this instance.
*/
public String getString() {
return lineSeparator;
diff --git a/src/main/java/org/apache/commons/io/TaggedIOException.java b/src/main/java/org/apache/commons/io/TaggedIOException.java
index 5eb0b5df596..d8d8a4834f2 100644
--- a/src/main/java/org/apache/commons/io/TaggedIOException.java
+++ b/src/main/java/org/apache/commons/io/TaggedIOException.java
@@ -57,8 +57,8 @@ public class TaggedIOException extends IOExceptionWithCause {
* }
*
*
- * @param throwable The Throwable object to check
- * @param tag tag object
+ * @param throwable The Throwable object to check.
+ * @param tag tag object.
* @return {@code true} if the throwable has the specified tag,
* otherwise {@code false}
*/
@@ -86,9 +86,9 @@ public static boolean isTaggedWith(final Throwable throwable, final Object tag)
* }
*
*
- * @param throwable an exception
- * @param tag tag object
- * @throws IOException original exception from the tagged decorator, if any
+ * @param throwable An exception.
+ * @param tag tag object.
+ * @throws IOException original exception from the tagged decorator, if any.
*/
public static void throwCauseIfTaggedWith(final Throwable throwable, final Object tag)
throws IOException {
@@ -105,8 +105,8 @@ public static void throwCauseIfTaggedWith(final Throwable throwable, final Objec
/**
* Constructs a tagged wrapper for the given exception.
*
- * @param original the exception to be tagged
- * @param tag tag of this exception
+ * @param original The exception to be tagged.
+ * @param tag tag of this exception.
*/
public TaggedIOException(final IOException original, final Serializable tag) {
super(original.getMessage(), original);
@@ -117,7 +117,7 @@ public TaggedIOException(final IOException original, final Serializable tag) {
* Returns the wrapped exception. The only difference to the overridden
* {@link Throwable#getCause()} method is the narrower return type.
*
- * @return wrapped exception
+ * @return wrapped exception.
*/
@Override
public synchronized IOException getCause() {
@@ -127,7 +127,7 @@ public synchronized IOException getCause() {
/**
* Returns the serializable tag object.
*
- * @return tag object
+ * @return tag object.
*/
public Serializable getTag() {
return tag;
diff --git a/src/main/java/org/apache/commons/io/ThreadMonitor.java b/src/main/java/org/apache/commons/io/ThreadMonitor.java
index 4c2c37a2d3b..f9fe24957c5 100644
--- a/src/main/java/org/apache/commons/io/ThreadMonitor.java
+++ b/src/main/java/org/apache/commons/io/ThreadMonitor.java
@@ -52,7 +52,7 @@ static Thread start(final Duration timeout) {
/**
* Starts monitoring the specified thread.
*
- * @param thread The thread to monitor
+ * @param thread The thread to monitor.
* @param timeout The timeout amount. or no timeout if the value is zero or less.
* @return The monitor thread or {@code null} if the timeout amount is not greater than zero.
*/
@@ -60,7 +60,7 @@ static Thread start(final Thread thread, final Duration timeout) {
if (timeout.isZero() || timeout.isNegative()) {
return null;
}
- final Thread monitor = new Thread(new ThreadMonitor(thread, timeout), ThreadMonitor.class.getSimpleName());
+ final Thread monitor = new Thread(new ThreadMonitor(thread, timeout), "commons-io-ThreadMonitor");
monitor.setDaemon(true);
monitor.start();
return monitor;
@@ -104,6 +104,7 @@ public void run() {
thread.interrupt();
} catch (final InterruptedException ignored) {
// timeout not reached
+ Thread.currentThread().interrupt();
}
}
}
diff --git a/src/main/java/org/apache/commons/io/ThreadUtils.java b/src/main/java/org/apache/commons/io/ThreadUtils.java
index fd3bd64c635..603bd4a1206 100644
--- a/src/main/java/org/apache/commons/io/ThreadUtils.java
+++ b/src/main/java/org/apache/commons/io/ThreadUtils.java
@@ -37,7 +37,7 @@ private static int getNanosOfMilli(final Duration duration) {
* {@link Thread#sleep(long, int)}} for further interesting details.
*
*
- * @param duration the sleep duration.
+ * @param duration The sleep duration.
* @throws InterruptedException if interrupted.
* @see Thread#sleep(long, int)
*/
diff --git a/src/main/java/org/apache/commons/io/UncheckedIOExceptions.java b/src/main/java/org/apache/commons/io/UncheckedIOExceptions.java
index f31043769b7..037c53764ea 100644
--- a/src/main/java/org/apache/commons/io/UncheckedIOExceptions.java
+++ b/src/main/java/org/apache/commons/io/UncheckedIOExceptions.java
@@ -34,8 +34,8 @@ final class UncheckedIOExceptions {
* This method exists because there is no String constructor in {@link UncheckedIOException}.
*
*
- * @param message the detail message.
- * @return a new {@link UncheckedIOException}.
+ * @param message The detail message.
+ * @return A new {@link UncheckedIOException}.
*/
public static UncheckedIOException create(final Object message) {
final String string = Objects.toString(message);
@@ -47,9 +47,10 @@ public static UncheckedIOException create(final Object message) {
*
* This method exists because there is no String constructor in {@link UncheckedIOException}.
*
+ *
* @param e cause the {@link IOException}.
- * @param message the detail message.
- * @return a new {@link UncheckedIOException}.
+ * @param message The detail message.
+ * @return A new {@link UncheckedIOException}.
*/
public static UncheckedIOException wrap(final IOException e, final Object message) {
return new UncheckedIOException(Objects.toString(message), e);
diff --git a/src/main/java/org/apache/commons/io/build/AbstractOrigin.java b/src/main/java/org/apache/commons/io/build/AbstractOrigin.java
index d84aefdb79a..9239ad75f06 100644
--- a/src/main/java/org/apache/commons/io/build/AbstractOrigin.java
+++ b/src/main/java/org/apache/commons/io/build/AbstractOrigin.java
@@ -31,6 +31,7 @@
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
+import java.net.URLConnection;
import java.nio.channels.Channel;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
@@ -43,8 +44,10 @@
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
+import java.time.Duration;
import java.util.Arrays;
import java.util.Objects;
+import java.util.stream.Stream;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IORandomAccessFile;
@@ -340,8 +343,8 @@
*
*
*
- * @param the type produced by the builder.
- * @param the concrete builder subclass type.
+ * @param The type produced by the builder.
+ * @param The concrete builder subclass type.
* @since 2.12.0
*/
public abstract class AbstractOrigin> extends AbstractSupplier {
@@ -353,8 +356,8 @@ public abstract class AbstractOrigin> extends
* instead.
*
*
- * @param the type of instances to build.
- * @param the type of builder subclass.
+ * @param The type of instances to build.
+ * @param The type of builder subclass.
*/
public abstract static class AbstractRandomAccessFileOrigin>
extends AbstractOrigin {
@@ -366,6 +369,7 @@ public abstract static class AbstractRandomAccessFileOrigin
*
* @param origin The origin, not null.
+ * @throws NullPointerException if {@code origin} is {@code null}.
*/
public AbstractRandomAccessFileOrigin(final T origin) {
super(origin);
@@ -437,6 +441,7 @@ public static class ByteArrayOrigin extends AbstractOrigin
* Constructs a new instance for the given origin.
*
* @param origin The origin, not null.
+ * @throws NullPointerException if {@code origin} is {@code null}.
*/
public ChannelOrigin(final Channel origin) {
super(origin);
@@ -563,6 +569,7 @@ public static class CharSequenceOrigin extends AbstractOrigin {
* Constructs a new instance for the given origin.
*
* @param origin The origin, not null.
+ * @throws NullPointerException if {@code origin} is {@code null}.
*/
public FileOrigin(final File origin) {
super(origin);
@@ -689,6 +697,7 @@ public static class InputStreamOrigin extends AbstractOrigin {
* Constructs a new instance for the given origin.
*
* @param origin The origin, not null.
+ * @throws NullPointerException if {@code origin} is {@code null}.
*/
public PathOrigin(final Path origin) {
super(origin);
@@ -892,6 +903,7 @@ public static class ReaderOrigin extends AbstractOrigin {
* Constructs a new instance for the given origin.
*
* @param origin The origin, not null.
+ * @throws NullPointerException if {@code origin} is {@code null}.
*/
public ReaderOrigin(final Reader origin) {
super(origin);
@@ -952,6 +964,80 @@ public Reader getReader(final Charset charset) throws IOException {
*/
public static class URIOrigin extends AbstractOrigin {
+ /**
+ * Options for connect and read from a URI.
+ *
+ * @since 2.22.0
+ */
+ public static final class URIOpenOption implements OpenOption {
+
+ /**
+ * Builds URIOpenOption.
+ */
+ public static class Builder extends AbstractSupplier {
+
+ private Duration connectTimeout;
+ private Duration readTimeout;
+
+ /**
+ * Constructs a new instance.
+ */
+ public Builder() {
+ // empty
+ }
+
+ @Override
+ public URIOpenOption get() {
+ return new URIOpenOption(this);
+ }
+
+ /**
+ * Sets the connect timeout duration.
+ *
+ * @param connectTimeout The connect timeout duration.
+ * @return {@code this instance}.
+ */
+ public Builder setConnectTimeout(final Duration connectTimeout) {
+ this.connectTimeout = connectTimeout;
+ return asThis();
+ }
+
+ /**
+ * Sets the read timeout duration.
+ *
+ * @param readTimeout The read timeout duration.
+ * @return {@code this instance}.
+ */
+ public Builder setReadTimeout(final Duration readTimeout) {
+ this.readTimeout = readTimeout;
+ return asThis();
+ }
+ }
+
+ /**
+ * Creates a new builder.
+ *
+ * @return A new builder.
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ private final Duration connectTimeout;
+
+ private final Duration readTimeout;
+
+ private URIOpenOption(final Builder builder) {
+ connectTimeout = builder.connectTimeout;
+ readTimeout = builder.readTimeout;
+ }
+
+ @Override
+ public String toString() {
+ return "URIOpenOption [connectTimeout=" + connectTimeout + ", readTimeout=" + readTimeout + "]";
+ }
+ }
+
private static final String SCHEME_HTTPS = "https";
private static final String SCHEME_HTTP = "http";
@@ -959,17 +1045,23 @@ public static class URIOrigin extends AbstractOrigin {
* Constructs a new instance for the given origin.
*
* @param origin The origin, not null.
+ * @throws NullPointerException if {@code origin} is {@code null}.
*/
public URIOrigin(final URI origin) {
super(origin);
}
+ /**
+ * {@inheritDoc}
+ *
+ * @see URIOpenOption
+ */
@Override
protected Channel getChannel(final OpenOption... options) throws IOException {
final URI uri = get();
final String scheme = uri.getScheme();
if (SCHEME_HTTP.equalsIgnoreCase(scheme) || SCHEME_HTTPS.equalsIgnoreCase(scheme)) {
- return Channels.newChannel(uri.toURL().openStream());
+ return Channels.newChannel(getInputStream(uri, options));
}
return Files.newByteChannel(getPath(), options);
}
@@ -979,20 +1071,52 @@ public File getFile() {
return getPath().toFile();
}
+ /**
+ * {@inheritDoc}
+ *
+ * Set timeouts with a {@link URIOpenOption}.
+ *
+ *
+ * @see URIOpenOption
+ * @see URLConnection#setConnectTimeout(int)
+ * @see URLConnection#setReadTimeout(int)
+ */
@Override
public InputStream getInputStream(final OpenOption... options) throws IOException {
final URI uri = get();
final String scheme = uri.getScheme();
if (SCHEME_HTTP.equalsIgnoreCase(scheme) || SCHEME_HTTPS.equalsIgnoreCase(scheme)) {
- return uri.toURL().openStream();
+ return getInputStream(uri, options);
}
return Files.newInputStream(getPath(), options);
}
+ private InputStream getInputStream(final URI uri, final OpenOption... options) throws IOException {
+ final URLConnection connection = uri.toURL().openConnection();
+ if (options != null) {
+ Stream.of(options).forEach(option -> {
+ if (option instanceof URIOpenOption) {
+ final URIOpenOption connOption = (URIOpenOption) option;
+ if (connOption.connectTimeout != null) {
+ connection.setConnectTimeout(toMillis(connOption.connectTimeout));
+ }
+ if (connOption.readTimeout != null) {
+ connection.setReadTimeout(toMillis(connOption.readTimeout));
+ }
+ }
+ });
+ }
+ return connection.getInputStream();
+ }
+
@Override
public Path getPath() {
return Paths.get(get());
}
+
+ private int toMillis(final Duration duration) {
+ return Math.toIntExact(duration.toMillis());
+ }
}
/**
@@ -1007,6 +1131,7 @@ public static class WriterOrigin extends AbstractOrigin {
* Constructs a new instance for the given origin.
*
* @param origin The origin, not null.
+ * @throws NullPointerException if {@code origin} is {@code null}.
*/
public WriterOrigin(final Writer origin) {
super(origin);
@@ -1057,15 +1182,16 @@ public Writer getWriter(final Charset charset, final OpenOption... options) thro
* Constructs a new instance for subclasses.
*
* @param origin The origin, not null.
+ * @throws NullPointerException if {@code origin} is {@code null}.
*/
protected AbstractOrigin(final T origin) {
this.origin = Objects.requireNonNull(origin, "origin");
}
/**
- * Gets the origin.
+ * Gets the origin, never null.
*
- * @return the origin.
+ * @return The origin, never null.
*/
@Override
public T get() {
@@ -1086,11 +1212,11 @@ public byte[] getByteArray() throws IOException {
/**
* Gets a portion of this origin as a byte array, if possible.
*
- * @param position the initial index of the range to be copied, inclusive.
+ * @param position The initial index of the range to be copied, inclusive.
* @param length How many bytes to copy.
* @return this origin as a byte array, if possible.
* @throws UnsupportedOperationException if the origin cannot be converted to a Path.
- * @throws ArithmeticException if the {@code position} overflows an int
+ * @throws ArithmeticException if the {@code position} overflows an int.
* @throws IOException if an I/O error occurs.
* @since 2.13.0
*/
@@ -1113,6 +1239,7 @@ public byte[] getByteArray(final long position, final int length) throws IOExcep
* @param The type of channel to return.
* @throws IOException If an I/O error occurs.
* @throws UnsupportedOperationException If this origin cannot be converted to a channel of the given type.
+ * @see #getChannel(OpenOption...)
* @since 2.21.0
*/
public final C getChannel(final Class channelType, final OpenOption... options) throws IOException {
@@ -1131,6 +1258,7 @@ public final C getChannel(final Class channelType, final
* @return A new Channel on the origin.
* @throws IOException If an I/O error occurs.
* @throws UnsupportedOperationException If this origin cannot be converted to a channel.
+ * @see #getChannel(Class, OpenOption...)
* @since 2.21.0
*/
protected Channel getChannel(final OpenOption... options) throws IOException {
@@ -1162,7 +1290,7 @@ public File getFile() {
/**
* Gets this origin as an InputStream, if possible.
*
- * @param options options specifying how the file is opened
+ * @param options options specifying how the file is opened.
* @return this origin as an InputStream, if possible.
* @throws IOException if an I/O error occurs.
* @throws UnsupportedOperationException if the origin cannot be converted to a Path.
@@ -1174,7 +1302,7 @@ public InputStream getInputStream(final OpenOption... options) throws IOExceptio
/**
* Gets this origin as an OutputStream, if possible.
*
- * @param options options specifying how the file is opened
+ * @param options options specifying how the file is opened.
* @return this origin as an OutputStream, if possible.
* @throws IOException if an I/O error occurs.
* @throws UnsupportedOperationException if the origin cannot be converted to a Path.
@@ -1209,14 +1337,19 @@ public RandomAccessFile getRandomAccessFile(final OpenOption... openOption) thro
/**
* Gets a new Reader on the origin, buffered by default.
*
- * @param charset the charset to use for decoding, null maps to the default Charset.
- * @return a new Reader on the origin.
+ * @param charset The charset to use for decoding, null maps to the default Charset.
+ * @return A new Reader on the origin.
* @throws IOException if an I/O error occurs opening the file.
*/
public Reader getReader(final Charset charset) throws IOException {
return Files.newBufferedReader(getPath(), Charsets.toCharset(charset));
}
+ /**
+ * Gets simple name of the underlying class.
+ *
+ * @return The simple name of the underlying class.
+ */
private String getSimpleClassName() {
return getClass().getSimpleName();
}
@@ -1224,9 +1357,9 @@ private String getSimpleClassName() {
/**
* Gets a new Writer on the origin, buffered by default.
*
- * @param charset the charset to use for encoding
- * @param options options specifying how the file is opened
- * @return a new Writer on the origin.
+ * @param charset The charset to use for encoding.
+ * @param options options specifying how the file is opened.
+ * @return A new Writer on the origin.
* @throws IOException if an I/O error occurs opening or creating the file.
* @throws UnsupportedOperationException if the origin cannot be converted to a Path.
*/
@@ -1237,7 +1370,7 @@ public Writer getWriter(final Charset charset, final OpenOption... options) thro
/**
* Gets the size of the origin, if possible.
*
- * @return the size of the origin in bytes or characters.
+ * @return The size of the origin in bytes or characters.
* @throws IOException if an I/O error occurs.
* @since 2.13.0
*/
diff --git a/src/main/java/org/apache/commons/io/build/AbstractOriginSupplier.java b/src/main/java/org/apache/commons/io/build/AbstractOriginSupplier.java
index ba8e6b393ba..5bf7cd0e3a4 100644
--- a/src/main/java/org/apache/commons/io/build/AbstractOriginSupplier.java
+++ b/src/main/java/org/apache/commons/io/build/AbstractOriginSupplier.java
@@ -45,8 +45,8 @@
/**
* Abstracts building an instance of type {@code T} where {@code T} is unbounded from a wrapped {@linkplain AbstractOrigin origin}.
*
- * @param the type of instances to build.
- * @param the type of builder subclass.
+ * @param The type of instances to build.
+ * @param The type of builder subclass.
* @since 2.12.0
*/
public abstract class AbstractOriginSupplier> extends AbstractSupplier {
@@ -54,8 +54,8 @@ public abstract class AbstractOriginSupplier checkOrigin() {
@@ -223,7 +223,7 @@ public AbstractOriginSupplier() {
/**
* Gets the origin.
*
- * @return the origin.
+ * @return The origin.
*/
protected AbstractOrigin, ?> getOrigin() {
return origin;
@@ -241,7 +241,7 @@ protected boolean hasOrigin() {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setByteArray(final byte[] origin) {
@@ -251,7 +251,7 @@ public B setByteArray(final byte[] origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
* @since 2.21.0
*/
@@ -262,7 +262,7 @@ public B setChannel(final Channel origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
* @since 2.13.0
*/
@@ -273,7 +273,7 @@ public B setCharSequence(final CharSequence origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setFile(final File origin) {
@@ -283,7 +283,7 @@ public B setFile(final File origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setFile(final String origin) {
@@ -293,7 +293,7 @@ public B setFile(final String origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setInputStream(final InputStream origin) {
@@ -303,7 +303,7 @@ public B setInputStream(final InputStream origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
protected B setOrigin(final AbstractOrigin, ?> origin) {
@@ -314,7 +314,7 @@ protected B setOrigin(final AbstractOrigin, ?> origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setOutputStream(final OutputStream origin) {
@@ -324,7 +324,7 @@ public B setOutputStream(final OutputStream origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setPath(final Path origin) {
@@ -334,7 +334,7 @@ public B setPath(final Path origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setPath(final String origin) {
@@ -344,7 +344,7 @@ public B setPath(final String origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
* @since 2.18.0
*/
@@ -355,7 +355,7 @@ public B setRandomAccessFile(final IORandomAccessFile origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
* @since 2.18.0
*/
@@ -366,7 +366,7 @@ public B setRandomAccessFile(final RandomAccessFile origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setReader(final Reader origin) {
@@ -376,7 +376,7 @@ public B setReader(final Reader origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setURI(final URI origin) {
@@ -386,7 +386,7 @@ public B setURI(final URI origin) {
/**
* Sets a new origin.
*
- * @param origin the new origin.
+ * @param origin The new origin.
* @return {@code this} instance.
*/
public B setWriter(final Writer origin) {
diff --git a/src/main/java/org/apache/commons/io/build/AbstractStreamBuilder.java b/src/main/java/org/apache/commons/io/build/AbstractStreamBuilder.java
index 541548c7295..8f59004ce3b 100644
--- a/src/main/java/org/apache/commons/io/build/AbstractStreamBuilder.java
+++ b/src/main/java/org/apache/commons/io/build/AbstractStreamBuilder.java
@@ -40,8 +40,8 @@
* buffer size checker, a buffer size default, buffer size maximum, Charset, Charset default, default size checker, and open options. A subclass may use all,
* some, or none of these properties in building instances of {@code T}.
*
- * @param the type of instances to build.
- * @param the type of builder subclass.
+ * @param The type of instances to build.
+ * @param The type of builder subclass.
* @since 2.12.0
*/
public abstract class AbstractStreamBuilder> extends AbstractOriginSupplier {
@@ -97,8 +97,8 @@ public AbstractStreamBuilder() {
/**
* Applies the buffer size request.
*
- * @param size the size request.
- * @return the size to use, usually the input, or can throw an unchecked exception, like {@link IllegalArgumentException}.
+ * @param size The size request.
+ * @return The size to use, usually the input, or can throw an unchecked exception, like {@link IllegalArgumentException}.
*/
private int checkBufferSize(final int size) {
return bufferSizeChecker.applyAsInt(size);
@@ -107,7 +107,7 @@ private int checkBufferSize(final int size) {
/**
* Gets the buffer size, defaults to {@link IOUtils#DEFAULT_BUFFER_SIZE} ({@value IOUtils#DEFAULT_BUFFER_SIZE}).
*
- * @return the buffer size, defaults to {@link IOUtils#DEFAULT_BUFFER_SIZE} ({@value IOUtils#DEFAULT_BUFFER_SIZE}).
+ * @return The buffer size, defaults to {@link IOUtils#DEFAULT_BUFFER_SIZE} ({@value IOUtils#DEFAULT_BUFFER_SIZE}).
*/
public int getBufferSize() {
return bufferSize;
@@ -116,12 +116,26 @@ public int getBufferSize() {
/**
* Gets the buffer size default, defaults to {@link IOUtils#DEFAULT_BUFFER_SIZE} ({@value IOUtils#DEFAULT_BUFFER_SIZE}).
*
- * @return the buffer size default, defaults to {@link IOUtils#DEFAULT_BUFFER_SIZE} ({@value IOUtils#DEFAULT_BUFFER_SIZE}).
+ * @return The buffer size default, defaults to {@link IOUtils#DEFAULT_BUFFER_SIZE} ({@value IOUtils#DEFAULT_BUFFER_SIZE}).
*/
public int getBufferSizeDefault() {
return bufferSizeDefault;
}
+ /**
+ * Gets a byte array from the origin.
+ *
+ * @return A byte array.
+ * @throws IllegalStateException if the {@code origin} is {@code null}.
+ * @throws UnsupportedOperationException if the origin cannot be converted to a byte array.
+ * @throws IOException if an I/O error occurs.
+ * @see AbstractOrigin#getByteArray()
+ * @since 2.22.0
+ */
+ public byte[] getByteArray() throws IOException {
+ return checkOrigin().getByteArray();
+ }
+
/**
* Gets a Channel from the origin with OpenOption[].
*
@@ -142,7 +156,7 @@ public C getChannel(final Class channelType) throws IOExc
/**
* Gets a CharSequence from the origin with a Charset.
*
- * @return An input stream
+ * @return An input stream.
* @throws IllegalStateException if the {@code origin} is {@code null}.
* @throws UnsupportedOperationException if the origin cannot be converted to a CharSequence.
* @throws IOException if an I/O error occurs.
@@ -156,7 +170,7 @@ public CharSequence getCharSequence() throws IOException {
/**
* Gets the Charset, defaults to {@link Charset#defaultCharset()}.
*
- * @return the Charset, defaults to {@link Charset#defaultCharset()}.
+ * @return The Charset, defaults to {@link Charset#defaultCharset()}.
*/
public Charset getCharset() {
return charset;
@@ -165,7 +179,7 @@ public Charset getCharset() {
/**
* Gets the Charset default, defaults to {@link Charset#defaultCharset()}.
*
- * @return the Charset default, defaults to {@link Charset#defaultCharset()}.
+ * @return The Charset default, defaults to {@link Charset#defaultCharset()}.
*/
public Charset getCharsetDefault() {
return charsetDefault;
@@ -174,7 +188,7 @@ public Charset getCharsetDefault() {
/**
* Gets a File from the origin.
*
- * @return A File
+ * @return A File.
* @throws IllegalStateException if the {@code origin} is {@code null}.
* @throws UnsupportedOperationException if the origin cannot be converted to a {@link File}.
* @see AbstractOrigin#getPath()
@@ -187,7 +201,7 @@ public File getFile() {
/**
* Gets an InputStream from the origin with OpenOption[].
*
- * @return An input stream
+ * @return An input stream.
* @throws IllegalStateException if the {@code origin} is {@code null}.
* @throws UnsupportedOperationException if the origin cannot be converted to an {@link InputStream}.
* @throws IOException if an I/O error occurs.
@@ -202,7 +216,7 @@ public InputStream getInputStream() throws IOException {
/**
* Gets the OpenOption array.
*
- * @return the OpenOption array.
+ * @return The OpenOption array, this is not a defensive copy, modify at your own risk.
*/
public OpenOption[] getOpenOptions() {
return openOptions;
@@ -211,7 +225,7 @@ public OpenOption[] getOpenOptions() {
/**
* Gets an OutputStream from the origin with OpenOption[].
*
- * @return An OutputStream
+ * @return An OutputStream.
* @throws IllegalStateException if the {@code origin} is {@code null}.
* @throws UnsupportedOperationException if the origin cannot be converted to an {@link OutputStream}.
* @throws IOException if an I/O error occurs.
@@ -226,7 +240,7 @@ public OutputStream getOutputStream() throws IOException {
/**
* Gets a Path from the origin.
*
- * @return A Path
+ * @return A Path.
* @throws IllegalStateException if the {@code origin} is {@code null}.
* @throws UnsupportedOperationException if the origin cannot be converted to a {@link Path}.
* @see AbstractOrigin#getPath()
@@ -239,7 +253,7 @@ public Path getPath() {
/**
* Gets a RandomAccessFile from the origin.
*
- * @return A RandomAccessFile
+ * @return A RandomAccessFile.
* @throws IllegalStateException if the {@code origin} is {@code null}.
* @throws UnsupportedOperationException if the origin cannot be converted to a {@link RandomAccessFile}.
* @throws IOException if an I/O error occurs.
@@ -252,7 +266,7 @@ public RandomAccessFile getRandomAccessFile() throws IOException {
/**
* Gets a Reader from the origin with a Charset.
*
- * @return A Reader
+ * @return A Reader.
* @throws IllegalStateException if the {@code origin} is {@code null}.
* @throws UnsupportedOperationException if the origin cannot be converted to a {@link Reader}.
* @throws IOException if an I/O error occurs.
@@ -285,7 +299,7 @@ public Writer getWriter() throws IOException {
* Subclasses may ignore this setting.
*
*
- * @param bufferSize the buffer size.
+ * @param bufferSize The buffer size, 0 resets to the default from {@link #getBufferSizeDefault()}.
* @return {@code this} instance.
*/
public B setBufferSize(final int bufferSize) {
@@ -299,7 +313,7 @@ public B setBufferSize(final int bufferSize) {
* Subclasses may ignore this setting.
*
*
- * @param bufferSize the buffer size, null resets to the default.
+ * @param bufferSize The buffer size, null resets to the default from {@link #getBufferSizeDefault()}.
* @return {@code this} instance.
*/
public B setBufferSize(final Integer bufferSize) {
@@ -310,7 +324,7 @@ public B setBufferSize(final Integer bufferSize) {
/**
* Sets the buffer size checker function. Throws a {@link IllegalArgumentException} by default.
*
- * @param bufferSizeChecker the buffer size checker function. null resets to the default behavior.
+ * @param bufferSizeChecker The buffer size checker function. null resets to the default behavior.
* @return {@code this} instance.
* @since 2.14.0
*/
@@ -325,11 +339,11 @@ public B setBufferSizeChecker(final IntUnaryOperator bufferSizeChecker) {
* Subclasses may ignore this setting.
*
*
- * @param bufferSizeDefault the buffer size, null resets to the default.
+ * @param bufferSizeDefault The buffer size, 0 resets to the default {@link IOUtils#DEFAULT_BUFFER_SIZE}.
* @return {@code this} instance.
*/
protected B setBufferSizeDefault(final int bufferSizeDefault) {
- this.bufferSizeDefault = bufferSizeDefault;
+ this.bufferSizeDefault = checkBufferSize(bufferSizeDefault > 0 ? bufferSizeDefault : IOUtils.DEFAULT_BUFFER_SIZE);
return asThis();
}
@@ -352,7 +366,7 @@ public B setBufferSizeMax(final int bufferSizeMax) {
* Subclasses may ignore this setting.
*
*
- * @param charset the Charset, null resets to the default.
+ * @param charset The Charset, null resets to the default.
* @return {@code this} instance.
*/
public B setCharset(final Charset charset) {
@@ -366,7 +380,7 @@ public B setCharset(final Charset charset) {
* Subclasses may ignore this setting.
*
*
- * @param charset the Charset name, null resets to the default.
+ * @param charset The Charset name, null resets to the default.
* @return {@code this} instance.
*/
public B setCharset(final String charset) {
@@ -379,7 +393,7 @@ public B setCharset(final String charset) {
* Subclasses may ignore this setting.
*
*
- * @param defaultCharset the Charset name, null resets to the default.
+ * @param defaultCharset The Charset name, null resets to the default.
* @return {@code this} instance.
*/
protected B setCharsetDefault(final Charset defaultCharset) {
@@ -388,7 +402,7 @@ protected B setCharsetDefault(final Charset defaultCharset) {
}
/**
- * Sets the OpenOption[].
+ * Sets the OpenOption array.
*
* Normally used with InputStream, OutputStream, and Writer.
*
@@ -396,7 +410,7 @@ protected B setCharsetDefault(final Charset defaultCharset) {
* Subclasses may ignore this setting.
*
*
- * @param openOptions the OpenOption[] name, null resets to the default.
+ * @param openOptions The OpenOption[] name, null resets to the default, a defensive copy is made.
* @return {@code this} instance.
* @since 2.13.0
* @see #setInputStream(InputStream)
@@ -404,7 +418,7 @@ protected B setCharsetDefault(final Charset defaultCharset) {
* @see #setWriter(Writer)
*/
public B setOpenOptions(final OpenOption... openOptions) {
- this.openOptions = openOptions != null ? openOptions : DEFAULT_OPEN_OPTIONS;
+ this.openOptions = openOptions != null ? openOptions.clone() : DEFAULT_OPEN_OPTIONS;
return asThis();
}
diff --git a/src/main/java/org/apache/commons/io/build/AbstractSupplier.java b/src/main/java/org/apache/commons/io/build/AbstractSupplier.java
index 6715ae61074..8319f4f92d5 100644
--- a/src/main/java/org/apache/commons/io/build/AbstractSupplier.java
+++ b/src/main/java/org/apache/commons/io/build/AbstractSupplier.java
@@ -118,8 +118,8 @@ public void test() {
}
*
*
- * @param the type of instances to build.
- * @param the type of builder subclass.
+ * @param The type of instances to build.
+ * @param The type of builder subclass.
* @see IOSupplier
* @since 2.12.0
*/
diff --git a/src/main/java/org/apache/commons/io/build/package-info.java b/src/main/java/org/apache/commons/io/build/package-info.java
index bda177c354c..5eed609d544 100644
--- a/src/main/java/org/apache/commons/io/build/package-info.java
+++ b/src/main/java/org/apache/commons/io/build/package-info.java
@@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
/**
* Provides classes to implement the builder pattern for IO classes.
*
@@ -49,5 +50,4 @@
*
* @since 2.12.0
*/
-
package org.apache.commons.io.build;
diff --git a/src/main/java/org/apache/commons/io/channels/ByteArraySeekableByteChannel.java b/src/main/java/org/apache/commons/io/channels/ByteArraySeekableByteChannel.java
index 4135a815e83..f98f232d414 100644
--- a/src/main/java/org/apache/commons/io/channels/ByteArraySeekableByteChannel.java
+++ b/src/main/java/org/apache/commons/io/channels/ByteArraySeekableByteChannel.java
@@ -24,12 +24,16 @@
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
+import java.nio.channels.NonWritableChannelException;
import java.nio.channels.SeekableByteChannel;
+import java.nio.file.OpenOption;
+import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.build.AbstractStreamBuilder;
/**
* A {@link SeekableByteChannel} implementation backed by a byte array.
@@ -38,25 +42,79 @@
* and it's not possible to {@link #position(long) set the position} or {@link #truncate(long) truncate} to a value bigger than that. The raw internal buffer is
* accessed via {@link ByteArraySeekableByteChannel#array()}.
*
+ *
+ * Building a read-only channel from an existing byte array is supported with:
+ *
+ *
+ * @since 2.22.0
+ */
+ public static class Builder extends AbstractStreamBuilder {
+
+ /**
+ * Constructs a new builder for {@link ByteArraySeekableByteChannel}.
+ */
+ public Builder() {
+ setByteArray(IOUtils.EMPTY_BYTE_ARRAY);
+ }
+
+ @Override
+ public ByteArraySeekableByteChannel get() throws IOException {
+ return new ByteArraySeekableByteChannel(this);
+ }
+ }
+
private static final int RESIZE_LIMIT = Integer.MAX_VALUE >> 1;
+ /**
+ * Constructs a new builder for {@link ByteArraySeekableByteChannel}.
+ *
+ * @return A new builder for {@link ByteArraySeekableByteChannel}.
+ * @since 2.22.0
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
/**
* Constructs a new channel backed directly by the given byte array.
*
- *
The channel initially contains the full contents of the array, with its
- * size set to {@code bytes.length} and its position set to {@code 0}.
+ *
+ * The channel initially contains the full contents of the array, with its size set to {@code bytes.length} and its position set to {@code 0}.
+ *
*
- *
Reads and writes operate on the shared array.
- * If a write operation extends beyond the current capacity, the channel will
- * automatically allocate a larger backing array and copy the existing contents.
+ *
+ * Reads and writes operate on the shared array. If a write operation extends beyond the current capacity, the channel will automatically allocate a larger
+ * backing array and copy the existing contents.
+ *
*
* @param bytes The byte array to wrap, must not be {@code null}
- * @return A new channel that uses the given array as its initial backing store
+ * @return A new channel that uses the given array as its initial backing store.
* @throws NullPointerException If {@code bytes} is {@code null}
* @see #array()
* @see ByteArrayInputStream#ByteArrayInputStream(byte[])
@@ -65,11 +123,11 @@ public static ByteArraySeekableByteChannel wrap(final byte[] bytes) {
Objects.requireNonNull(bytes, "bytes");
return new ByteArraySeekableByteChannel(bytes);
}
-
private byte[] data;
private volatile boolean closed;
- private int position;
+ private long position;
private int size;
+ private final boolean isWritable;
private final ReentrantLock lock = new ReentrantLock();
/**
@@ -84,10 +142,19 @@ public ByteArraySeekableByteChannel() {
this(IOUtils.DEFAULT_BUFFER_SIZE);
}
+ private ByteArraySeekableByteChannel(final Builder builder) throws IOException {
+ this.data = builder.getByteArray();
+ this.size = data.length;
+ final OpenOption[] openOptions = builder.getOpenOptions();
+ Arrays.sort(openOptions);
+ this.isWritable = openOptions.length == 0 || Arrays.binarySearch(openOptions, StandardOpenOption.WRITE) >= 0
+ || Arrays.binarySearch(openOptions, StandardOpenOption.APPEND) >= 0;
+ }
+
private ByteArraySeekableByteChannel(final byte[] data) {
this.data = data;
- this.position = 0;
this.size = data.length;
+ this.isWritable = true;
}
/**
@@ -104,8 +171,7 @@ public ByteArraySeekableByteChannel(final int size) {
throw new IllegalArgumentException("Size must be non-negative");
}
this.data = new byte[size];
- this.position = 0;
- this.size = 0;
+ this.isWritable = true;
}
/**
@@ -126,11 +192,16 @@ private void checkOpen() throws ClosedChannelException {
}
}
- private int checkRange(final long newSize, final String method) {
- if (newSize < 0L || newSize > IOUtils.SOFT_MAX_ARRAY_LENGTH) {
- throw new IllegalArgumentException(String.format("%s must be in range [0..%,d]: %,d", method, IOUtils.SOFT_MAX_ARRAY_LENGTH, newSize));
+ private void checkRange(final long newSize, final String method) {
+ if (newSize < 0L) {
+ throw new IllegalArgumentException(String.format("%s must be positive: %,d", method, newSize));
+ }
+ }
+
+ private void checkWritable() {
+ if (!isWritable) {
+ throw new NonWritableChannelException();
}
- return (int) newSize;
}
@Override
@@ -166,10 +237,10 @@ public long position() throws ClosedChannelException {
@Override
public SeekableByteChannel position(final long newPosition) throws IOException {
checkOpen();
- final int intPos = checkRange(newPosition, "position()");
+ checkRange(newPosition, "position()");
lock.lock();
try {
- position = intPos;
+ position = newPosition;
} finally {
lock.unlock();
}
@@ -181,15 +252,18 @@ public int read(final ByteBuffer buf) throws IOException {
checkOpen();
lock.lock();
try {
+ if (position > Integer.MAX_VALUE) {
+ return IOUtils.EOF;
+ }
int wanted = buf.remaining();
- final int possible = size - position;
+ final int possible = size - (int) position;
if (possible <= 0) {
return IOUtils.EOF;
}
if (wanted > possible) {
wanted = possible;
}
- buf.put(data, position, wanted);
+ buf.put(data, (int) position, wanted);
position += wanted;
return wanted;
} finally {
@@ -229,7 +303,7 @@ public long size() throws ClosedChannelException {
* The returned array is a copy of the internal buffer, sized to the actual data stored in this channel.
*
*
- * @return a new byte array containing the data stored in this channel.
+ * @return A new byte array containing the data stored in this channel.
*/
public byte[] toByteArray() {
return Arrays.copyOf(data, size);
@@ -238,14 +312,15 @@ public byte[] toByteArray() {
@Override
public SeekableByteChannel truncate(final long newSize) throws ClosedChannelException {
checkOpen();
- final int intSize = checkRange(newSize, "truncate()");
+ checkWritable();
+ checkRange(newSize, "truncate()");
lock.lock();
try {
- if (size > intSize) {
- size = intSize;
+ if (size > newSize) {
+ size = (int) newSize;
}
- if (position > intSize) {
- position = intSize;
+ if (position > newSize) {
+ position = newSize;
}
} finally {
lock.unlock();
@@ -256,21 +331,30 @@ public SeekableByteChannel truncate(final long newSize) throws ClosedChannelExce
@Override
public int write(final ByteBuffer b) throws IOException {
checkOpen();
+ checkWritable();
+ //
+ if (position > Integer.MAX_VALUE) {
+ throw new IOException("position > Integer.MAX_VALUE");
+ }
lock.lock();
try {
final int wanted = b.remaining();
- final int possibleWithoutResize = Math.max(0, size - position);
- if (wanted > possibleWithoutResize) {
- final int newSize = position + wanted;
- if (newSize < 0 || newSize > IOUtils.SOFT_MAX_ARRAY_LENGTH) { // overflow
- throw new OutOfMemoryError("required array size " + Integer.toUnsignedString(newSize) + " too large");
- }
- resize(newSize);
+ // intPos <= Integer.MAX_VALUE
+ final int intPos = (int) position;
+ final long newPosition = position + wanted;
+ if (newPosition > IOUtils.SOFT_MAX_ARRAY_LENGTH) {
+ throw new IOException(String.format("Requested array size %,d is too large.", newPosition));
}
- b.get(data, position, wanted);
- position += wanted;
- if (size < position) {
- size = position;
+ if (newPosition > size) {
+ final int newPositionInt = (int) newPosition;
+ // Ensure that newPositionInt ≤ data.length
+ resize(newPositionInt);
+ size = newPositionInt;
+ }
+ b.get(data, intPos, wanted);
+ position = newPosition;
+ if (size < intPos) {
+ size = intPos;
}
return wanted;
} finally {
diff --git a/src/main/java/org/apache/commons/io/channels/CloseShieldChannel.java b/src/main/java/org/apache/commons/io/channels/CloseShieldChannel.java
index a9a462da73b..987e8427c7c 100644
--- a/src/main/java/org/apache/commons/io/channels/CloseShieldChannel.java
+++ b/src/main/java/org/apache/commons/io/channels/CloseShieldChannel.java
@@ -19,7 +19,16 @@
import java.io.Closeable;
import java.lang.reflect.Proxy;
+import java.nio.channels.AsynchronousChannel;
+import java.nio.channels.ByteChannel;
import java.nio.channels.Channel;
+import java.nio.channels.GatheringByteChannel;
+import java.nio.channels.InterruptibleChannel;
+import java.nio.channels.NetworkChannel;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.ScatteringByteChannel;
+import java.nio.channels.SeekableByteChannel;
+import java.nio.channels.WritableByteChannel;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
@@ -28,8 +37,24 @@
* Creates a close-shielding proxy for a {@link Channel}.
*
*
- * The returned proxy will implement all {@link Channel} sub-interfaces that the delegate implements.
+ * The returned proxy implements all {@link Channel} sub-interfaces that are both supported by this implementation and actually implemented by the given
+ * delegate.
*
+ *
+ * The following interfaces are supported:
+ *
+ *
+ *
{@link AsynchronousChannel}
+ *
{@link ByteChannel}
+ *
{@link Channel}
+ *
{@link GatheringByteChannel}
+ *
{@link InterruptibleChannel}
+ *
{@link NetworkChannel}
+ *
{@link ReadableByteChannel}
+ *
{@link ScatteringByteChannel}
+ *
{@link SeekableByteChannel}
+ *
{@link WritableByteChannel}
+ *
*
* @see Channel
* @see Closeable
@@ -40,11 +65,15 @@ public final class CloseShieldChannel {
private static final Class>[] EMPTY = {};
private static Set> collectChannelInterfaces(final Class> type, final Set> out) {
+ Class> currentType = type;
// Visit interfaces
- for (final Class> iface : type.getInterfaces()) {
- if (Channel.class.isAssignableFrom(iface) && out.add(iface)) {
- collectChannelInterfaces(iface, out);
+ while (currentType != null) {
+ for (final Class> iface : currentType.getInterfaces()) {
+ if (CloseShieldChannelHandler.isSupported(iface) && out.add(iface)) {
+ collectChannelInterfaces(iface, out);
+ }
}
+ currentType = currentType.getSuperclass();
}
return out;
}
@@ -53,8 +82,10 @@ private static Set> collectChannelInterfaces(final Class> type, final
* Wraps a channel to shield it from being closed.
*
* @param channel The underlying channel to shield, not {@code null}.
- * @param Any Channel type (interface or class).
+ * @param A supported channel type.
* @return A proxy that shields {@code close()} and enforces closed semantics on other calls.
+ * @throws ClassCastException if {@code T} is not a supported channel type.
+ * @throws NullPointerException if {@code channel} is {@code null}.
*/
@SuppressWarnings({ "unchecked", "resource" }) // caller closes
public static T wrap(final T channel) {
diff --git a/src/main/java/org/apache/commons/io/channels/CloseShieldChannelHandler.java b/src/main/java/org/apache/commons/io/channels/CloseShieldChannelHandler.java
index f13b101c197..822c6b6186b 100644
--- a/src/main/java/org/apache/commons/io/channels/CloseShieldChannelHandler.java
+++ b/src/main/java/org/apache/commons/io/channels/CloseShieldChannelHandler.java
@@ -21,14 +21,44 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
+import java.nio.channels.AsynchronousChannel;
+import java.nio.channels.ByteChannel;
import java.nio.channels.Channel;
import java.nio.channels.ClosedChannelException;
+import java.nio.channels.GatheringByteChannel;
+import java.nio.channels.InterruptibleChannel;
import java.nio.channels.NetworkChannel;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.ScatteringByteChannel;
import java.nio.channels.SeekableByteChannel;
+import java.nio.channels.WritableByteChannel;
+import java.util.Collections;
+import java.util.HashSet;
import java.util.Objects;
+import java.util.Set;
+/**
+ * An {@link InvocationHandler} supporting the implementation of {@link CloseShieldChannel}.
+ */
final class CloseShieldChannelHandler implements InvocationHandler {
+ private static final Set> SUPPORTED_INTERFACES;
+
+ static {
+ final Set> interfaces = new HashSet<>();
+ interfaces.add(AsynchronousChannel.class);
+ interfaces.add(ByteChannel.class);
+ interfaces.add(Channel.class);
+ interfaces.add(GatheringByteChannel.class);
+ interfaces.add(InterruptibleChannel.class);
+ interfaces.add(NetworkChannel.class);
+ interfaces.add(ReadableByteChannel.class);
+ interfaces.add(ScatteringByteChannel.class);
+ interfaces.add(SeekableByteChannel.class);
+ interfaces.add(WritableByteChannel.class);
+ SUPPORTED_INTERFACES = Collections.unmodifiableSet(interfaces);
+ }
+
/**
* Tests whether the given method is allowed to be called after the shield is closed.
*
@@ -42,6 +72,10 @@ private static boolean isAllowedAfterClose(final Class> declaringClass, final
return parameterCount == 0 && name.equals("supportedOptions") && NetworkChannel.class.equals(declaringClass);
}
+ static boolean isSupported(final Class> interfaceClass) {
+ return SUPPORTED_INTERFACES.contains(interfaceClass);
+ }
+
/**
* Tests whether the given method returns 'this' (the channel) as per JDK spec.
*
@@ -123,7 +157,7 @@ private Object invokeObjectMethod(final Object proxy, final Method method, final
return false;
}
default:
- // Not possible, all non-final Object methods are handled above
+ // Not possible, all non-final Object methods are handled above.
return null;
}
}
diff --git a/src/main/java/org/apache/commons/io/channels/FileChannels.java b/src/main/java/org/apache/commons/io/channels/FileChannels.java
index 30a80e8ab6b..7ef9e3f82c9 100644
--- a/src/main/java/org/apache/commons/io/channels/FileChannels.java
+++ b/src/main/java/org/apache/commons/io/channels/FileChannels.java
@@ -24,6 +24,7 @@
import java.nio.channels.SeekableByteChannel;
import java.util.Objects;
+import org.apache.commons.io.Buffers;
import org.apache.commons.io.IOUtils;
/**
@@ -67,36 +68,38 @@ public static boolean contentEquals(final ReadableByteChannel channel1, final Re
// Don't use ByteBuffer#compact() to avoid extra copying.
final ByteBuffer c1Buffer = ByteBuffer.allocateDirect(bufferCapacity);
final ByteBuffer c2Buffer = ByteBuffer.allocateDirect(bufferCapacity);
- int c1NumRead = 0;
- int c2NumRead = 0;
- boolean c1Read0 = false;
- boolean c2Read0 = false;
- // If a channel is a non-blocking channel, it may return 0 bytes read for any given call.
- while (true) {
- if (!c2Read0) {
- c1NumRead = readToLimit(channel1, c1Buffer);
- c1Buffer.clear();
- c1Read0 = c1NumRead == 0;
- }
- if (!c1Read0) {
- c2NumRead = readToLimit(channel2, c2Buffer);
- c2Buffer.clear();
- c2Read0 = c2NumRead == 0;
- }
- if (c1NumRead == IOUtils.EOF && c2NumRead == IOUtils.EOF) {
- return c1Buffer.equals(c2Buffer);
- }
- if (c1NumRead == 0 || c2NumRead == 0) {
- // 0 may be returned from a non-blocking channel.
- Thread.yield();
- continue;
- }
- if (c1NumRead != c2NumRead) {
- return false;
- }
- if (!c1Buffer.equals(c2Buffer)) {
- return false;
+ try {
+ int c1NumRead = 0;
+ int c2NumRead = 0;
+ boolean c1Read0 = false;
+ boolean c2Read0 = false;
+ // If a channel is a non-blocking channel, it may return 0 bytes read for any given call.
+ while (true) {
+ if (!c2Read0) {
+ c1NumRead = readToLimit(channel1, c1Buffer);
+ c1Buffer.clear();
+ c1Read0 = c1NumRead == 0;
+ }
+ if (!c1Read0) {
+ c2NumRead = readToLimit(channel2, c2Buffer);
+ c2Buffer.clear();
+ c2Read0 = c2NumRead == 0;
+ }
+ if (c1NumRead == IOUtils.EOF && c2NumRead == IOUtils.EOF) {
+ return c1Buffer.equals(c2Buffer);
+ }
+ if (c1NumRead == 0 || c2NumRead == 0) {
+ // 0 may be returned from a non-blocking channel.
+ Thread.yield();
+ continue;
+ }
+ if (c1NumRead != c2NumRead || !c1Buffer.equals(c2Buffer)) {
+ return false;
+ }
}
+ } finally {
+ Buffers.clear(c1Buffer);
+ Buffers.clear(c2Buffer);
}
}
@@ -135,7 +138,7 @@ public static boolean contentEquals(final SeekableByteChannel channel1, final Se
*
* @param channel The source channel.
* @param dst The buffer into which bytes are to be transferred.
- * @return The number of bytes read, never zero, or {@code -1} if the channel has reached end-of-stream
+ * @return The number of bytes read, never zero, or {@code -1} if the channel has reached end-of-stream.
* @throws IOException If some other I/O error occurs.
* @throws IllegalArgumentException If there is room in the given buffer.
*/
diff --git a/src/main/java/org/apache/commons/io/channels/FilterByteChannel.java b/src/main/java/org/apache/commons/io/channels/FilterByteChannel.java
new file mode 100644
index 00000000000..56f7d6d7fc2
--- /dev/null
+++ b/src/main/java/org/apache/commons/io/channels/FilterByteChannel.java
@@ -0,0 +1,125 @@
+/*
+ * 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.io.channels;
+
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
+import java.io.FilterReader;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.ByteChannel;
+
+import org.apache.commons.io.input.ProxyInputStream;
+import org.apache.commons.io.input.ProxyReader;
+import org.apache.commons.io.output.ProxyOutputStream;
+import org.apache.commons.io.output.ProxyWriter;
+
+/**
+ * A {@link ByteChannel} filter which delegates to the wrapped {@link ByteChannel}.
+ *
+ * A {@code FilterByteChannel} wraps some other channel, which it uses as its basic source of data, possibly transforming the data along the way or providing
+ * additional functionality. The class {@code FilterByteChannel} itself simply overrides methods of {@code ByteChannel} with versions that pass all requests to
+ * the wrapped channel. Subclasses of {@code FilterByteChannel} may of course override any methods declared or inherited by {@code FilterByteChannel}, and may
+ * also provide additional fields and methods.
+ *
+ *
+ * You construct s simple instance with the {@link FilterByteChannel#FilterByteChannel(ByteChannel) channel constructor} and more advanced instances through the
+ * {@link Builder}.
+ *
+ *
+ * @param The {@link ByteChannel} type.
+ * @see FilterInputStream
+ * @see FilterOutputStream
+ * @see FilterReader
+ * @see FilterWritableByteChannel
+ * @see ProxyInputStream
+ * @see ProxyOutputStream
+ * @see ProxyReader
+ * @see ProxyWriter
+ * @since 2.22.0
+ */
+public class FilterByteChannel extends FilterChannel implements ByteChannel {
+
+ /**
+ * Builds instances of {@link FilterByteChannel} for subclasses.
+ *
+ * @param The {@link FilterByteChannel} type.
+ * @param The {@link ByteChannel} type wrapped by the FilterChannel.
+ * @param The builder type.
+ */
+ public abstract static class AbstractBuilder, C extends ByteChannel, B extends AbstractBuilder>
+ extends FilterChannel.AbstractBuilder {
+
+ /**
+ * Constructs a new builder for {@link FilterByteChannel}.
+ */
+ protected AbstractBuilder() {
+ // empty
+ }
+ }
+
+ /**
+ * Builds instances of {@link FilterByteChannel}.
+ */
+ public static class Builder extends AbstractBuilder, ByteChannel, Builder> {
+
+ /**
+ * Builds instances of {@link FilterByteChannel}.
+ */
+ protected Builder() {
+ // empty
+ }
+
+ @Override
+ public FilterByteChannel get() throws IOException {
+ return new FilterByteChannel<>(this);
+ }
+ }
+
+ /**
+ * Creates a new {@link Builder}.
+ *
+ * @return A new {@link Builder}.
+ */
+ public static Builder forByteChannel() {
+ return new Builder();
+ }
+
+ FilterByteChannel(final AbstractBuilder, ?, ?> builder) throws IOException {
+ super(builder);
+ }
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param byteChannel The channel to wrap.
+ */
+ public FilterByteChannel(final C byteChannel) {
+ super(byteChannel);
+ }
+
+ @Override
+ public int read(final ByteBuffer dst) throws IOException {
+ return channel.read(dst);
+ }
+
+ @Override
+ public int write(final ByteBuffer src) throws IOException {
+ return channel.write(src);
+ }
+}
diff --git a/src/main/java/org/apache/commons/io/channels/FilterChannel.java b/src/main/java/org/apache/commons/io/channels/FilterChannel.java
new file mode 100644
index 00000000000..08a48fe1e8d
--- /dev/null
+++ b/src/main/java/org/apache/commons/io/channels/FilterChannel.java
@@ -0,0 +1,146 @@
+/*
+ * 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.io.channels;
+
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
+import java.io.FilterReader;
+import java.io.IOException;
+import java.nio.channels.Channel;
+
+import org.apache.commons.io.build.AbstractStreamBuilder;
+import org.apache.commons.io.input.ProxyInputStream;
+import org.apache.commons.io.input.ProxyReader;
+import org.apache.commons.io.output.ProxyOutputStream;
+import org.apache.commons.io.output.ProxyWriter;
+
+/**
+ * A {@link Channel} filter which delegates to the wrapped {@link Channel}.
+ *
+ * A {@code FilterChannel} wraps some other channel, which it uses as its basic source of data, possibly transforming the data along the way or providing
+ * additional functionality. The class {@code FilterChannel} itself simply overrides methods of {@code Channel} with versions that pass all requests to the
+ * wrapped channel. Subclasses of {@code FilterChannel} may of course override any methods declared or inherited by {@code FilterChannel}, and may also provide
+ * additional fields and methods.
+ *
+ *
+ * You construct s simple instance with the {@link FilterChannel#FilterChannel(Channel) channel constructor} and more advanced instances through the
+ * {@link Builder}.
+ *
+ *
+ * @param The {@link Channel} type.
+ * @see FilterInputStream
+ * @see FilterOutputStream
+ * @see FilterReader
+ * @see FilterWritableByteChannel
+ * @see ProxyInputStream
+ * @see ProxyOutputStream
+ * @see ProxyReader
+ * @see ProxyWriter
+ * @since 2.22.0
+ */
+public class FilterChannel implements Channel {
+
+ /**
+ * Builds instances of {@link FilterChannel} for subclasses.
+ *
+ * @param The {@link FilterChannel} type.
+ * @param The {@link Channel} type wrapped by the FilterChannel.
+ * @param The builder type.
+ */
+ public abstract static class AbstractBuilder, C extends Channel, B extends AbstractBuilder>
+ extends AbstractStreamBuilder> {
+
+ /**
+ * Constructs instance for subclasses.
+ */
+ protected AbstractBuilder() {
+ // empty
+ }
+ }
+
+ /**
+ * Builds instances of {@link FilterChannel}.
+ */
+ public static class Builder extends AbstractBuilder, Channel, Builder> {
+
+ /**
+ * Builds instances of {@link FilterChannel}.
+ */
+ protected Builder() {
+ // empty
+ }
+
+ @Override
+ public FilterChannel get() throws IOException {
+ return new FilterChannel<>(this);
+ }
+ }
+
+ /**
+ * Creates a new {@link Builder}.
+ *
+ * @return A new {@link Builder}.
+ */
+ public static Builder forChannel() {
+ return new Builder();
+ }
+
+ final C channel;
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param builder The source builder.
+ * @throws IOException if an I/O error occurs.
+ */
+ @SuppressWarnings("unchecked")
+ FilterChannel(final AbstractBuilder, ?, ?> builder) throws IOException {
+ channel = (C) builder.getChannel(Channel.class);
+ }
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param channel The channel to wrap.
+ */
+ public FilterChannel(final C channel) {
+ this.channel = channel;
+ }
+
+ @Override
+ public void close() throws IOException {
+ channel.close();
+ }
+
+ @Override
+ public boolean isOpen() {
+ return channel.isOpen();
+ }
+
+ /**
+ * Unwraps this instance by returning the underlying {@link Channel} of type {@code C}.
+ *
+ * Use with caution.
+ *
+ *
+ * @return The underlying channel of type {@code C}.
+ */
+ public C unwrap() {
+ return channel;
+ }
+}
diff --git a/src/test/java/org/apache/commons/io/channels/FileChannelProxy.java b/src/main/java/org/apache/commons/io/channels/FilterFileChannel.java
similarity index 57%
rename from src/test/java/org/apache/commons/io/channels/FileChannelProxy.java
rename to src/main/java/org/apache/commons/io/channels/FilterFileChannel.java
index ce7c0daddf7..6b9e23ddd41 100644
--- a/src/test/java/org/apache/commons/io/channels/FileChannelProxy.java
+++ b/src/main/java/org/apache/commons/io/channels/FilterFileChannel.java
@@ -20,20 +20,90 @@
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
+import java.nio.channels.Channel;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
+import java.util.Objects;
+
+import org.apache.commons.io.build.AbstractStreamBuilder;
/**
- * Proxies a FileChannel.
+ * Filters a {@link FileChannel}.
+ *
+ * A {@code FilterFileChannel} wraps some other channel, which it uses as its basic source of data, possibly transforming the data along the way or providing
+ * additional functionality. The class {@code FilterFileChannel} itself simply overrides methods of {@code FileChannel} with versions that pass all requests to
+ * the wrapped channel. Subclasses of {@code FilterFileChannel} may of course override any methods declared or inherited by {@code FilterFileChannel}, and may
+ * also provide additional fields and methods.
+ *
+ *
+ * You construct s simple instance with the {@link FilterFileChannel#FilterFileChannel(FileChannel) channel constructor} and more advanced instances through the
+ * {@link Builder}.
+ *
+ *
+ * @since 2.22.0
*/
-class FileChannelProxy extends FileChannel {
+public class FilterFileChannel extends FileChannel {
+
+ /**
+ * Builds instances of {@link FilterFileChannel} for subclasses.
+ *
+ * @param The {@link FilterFileChannel} type.
+ * @param The {@link Channel} type wrapped by the FilterChannel.
+ * @param The builder type.
+ */
+ public abstract static class AbstractBuilder>
+ extends AbstractStreamBuilder> {
+
+ /**
+ * Constructs instance for subclasses.
+ */
+ protected AbstractBuilder() {
+ // empty
+ }
+ }
+
+ /**
+ * Builds instances of {@link FilterFileChannel}.
+ */
+ public static class Builder extends AbstractBuilder {
- FileChannel fileChannel;
+ /**
+ * Builds instances of {@link FilterChannel}.
+ */
+ protected Builder() {
+ // empty
+ }
+
+ @Override
+ public FilterFileChannel get() throws IOException {
+ return new FilterFileChannel(this);
+ }
+ }
- FileChannelProxy(final FileChannel fileChannel) {
- this.fileChannel = fileChannel;
+ /**
+ * Creates a new {@link Builder}.
+ *
+ * @return A new {@link Builder}.
+ */
+ public static Builder forFilterFileChannel() {
+ return new Builder();
+ }
+
+ final FileChannel fileChannel;
+
+ private FilterFileChannel(final Builder builder) throws IOException {
+ this.fileChannel = builder.getChannel(FileChannel.class);
+ }
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param fileChannel The file channel to wrap.
+ */
+ public FilterFileChannel(final FileChannel fileChannel) {
+ this.fileChannel = Objects.requireNonNull(fileChannel, "fileChannel");
}
@Override
@@ -121,6 +191,18 @@ public FileLock tryLock(final long position, final long size, final boolean shar
return fileChannel.tryLock(position, size, shared);
}
+ /**
+ * Unwraps this instance by returning the underlying {@link FileChannel}.
+ *
+ * Use with caution.
+ *
+ *
+ * @return The underlying {@link FileChannel}.
+ */
+ public FileChannel unwrap() {
+ return fileChannel;
+ }
+
@Override
public int write(final ByteBuffer src) throws IOException {
return fileChannel.write(src);
diff --git a/src/main/java/org/apache/commons/io/channels/FilterReadableByteChannel.java b/src/main/java/org/apache/commons/io/channels/FilterReadableByteChannel.java
new file mode 100644
index 00000000000..8fa453e0f4e
--- /dev/null
+++ b/src/main/java/org/apache/commons/io/channels/FilterReadableByteChannel.java
@@ -0,0 +1,120 @@
+/*
+ * 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.io.channels;
+
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
+import java.io.FilterReader;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.ReadableByteChannel;
+
+import org.apache.commons.io.input.ProxyInputStream;
+import org.apache.commons.io.input.ProxyReader;
+import org.apache.commons.io.output.ProxyOutputStream;
+import org.apache.commons.io.output.ProxyWriter;
+
+/**
+ * A {@link ReadableByteChannel} filter which delegates to the wrapped {@link ReadableByteChannel}.
+ *
+ * A {@code FilterReadableByteChannel} wraps some other channel, which it uses as its basic source of data, possibly transforming the data along the way or
+ * providing additional functionality. The class {@code FilterReadableByteChannel} itself simply overrides methods of {@code ReadableByteChannel} with versions
+ * that pass all requests to the wrapped channel. Subclasses of {@code FilterReadableByteChannel} may of course override any methods declared or inherited by
+ * {@code FilterReadableByteChannel}, and may also provide additional fields and methods.
+ *
+ *
+ * You construct s simple instance with the {@link FilterReadableByteChannel#FilterReadableByteChannel(ReadableByteChannel) channel constructor} and more
+ * advanced instances through the {@link Builder}.
+ *
+ *
+ * @param The {@link ReadableByteChannel} type.
+ * @see FilterInputStream
+ * @see FilterOutputStream
+ * @see FilterReader
+ * @see FilterWritableByteChannel
+ * @see ProxyInputStream
+ * @see ProxyOutputStream
+ * @see ProxyReader
+ * @see ProxyWriter
+ * @since 2.22.0
+ */
+public class FilterReadableByteChannel extends FilterChannel implements ReadableByteChannel {
+
+ /**
+ * Builds instances of {@link FilterReadableByteChannel} for subclasses.
+ *
+ * @param The {@link FilterReadableByteChannel} type.
+ * @param The {@link ReadableByteChannel} type wrapped by the FilterChannel.
+ * @param The builder type.
+ */
+ public abstract static class AbstractBuilder, C extends ReadableByteChannel, B extends AbstractBuilder>
+ extends FilterChannel.AbstractBuilder {
+
+ /**
+ * Constructs a new builder for {@link FilterReadableByteChannel}.
+ */
+ public AbstractBuilder() {
+ // empty
+ }
+ }
+
+ /**
+ * Builds instances of {@link FilterByteChannel}.
+ */
+ public static class Builder extends AbstractBuilder, ReadableByteChannel, Builder> {
+
+ /**
+ * Builds instances of {@link FilterByteChannel}.
+ */
+ protected Builder() {
+ // empty
+ }
+
+ @Override
+ public FilterReadableByteChannel get() throws IOException {
+ return new FilterReadableByteChannel<>(this);
+ }
+ }
+
+ /**
+ * Creates a new {@link Builder}.
+ *
+ * @return A new {@link Builder}.
+ */
+ public static Builder forReadableByteChannel() {
+ return new Builder();
+ }
+
+ FilterReadableByteChannel(final Builder builder) throws IOException {
+ super(builder);
+ }
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param channel The channel to wrap.
+ */
+ public FilterReadableByteChannel(final C channel) {
+ super(channel);
+ }
+
+ @Override
+ public int read(final ByteBuffer dst) throws IOException {
+ return channel.read(dst);
+ }
+}
diff --git a/src/main/java/org/apache/commons/io/channels/FilterSeekableByteChannel.java b/src/main/java/org/apache/commons/io/channels/FilterSeekableByteChannel.java
new file mode 100644
index 00000000000..58c9847c7c1
--- /dev/null
+++ b/src/main/java/org/apache/commons/io/channels/FilterSeekableByteChannel.java
@@ -0,0 +1,134 @@
+/*
+ * 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.io.channels;
+
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
+import java.io.FilterReader;
+import java.io.IOException;
+import java.nio.channels.SeekableByteChannel;
+
+import org.apache.commons.io.input.ProxyInputStream;
+import org.apache.commons.io.input.ProxyReader;
+import org.apache.commons.io.output.ProxyOutputStream;
+import org.apache.commons.io.output.ProxyWriter;
+
+/**
+ * A {@link SeekableByteChannel} filter which delegates to the wrapped {@link SeekableByteChannel}.
+ *
+ * A {@code FilterSeekableByteChannel} wraps some other channel, which it uses as its basic source of data, possibly transforming the data along the way or
+ * providing additional functionality. The class {@code FilterSeekableByteChannel} itself simply overrides methods of {@code SeekableByteChannel} with versions
+ * that pass all requests to the wrapped channel. Subclasses of {@code FilterSeekableByteChannel} may of course override any methods declared or inherited by
+ * {@code FilterSeekableByteChannel}, and may also provide additional fields and methods.
+ *
+ *
+ * You construct s simple instance with the {@link FilterSeekableByteChannel#FilterSeekableByteChannel(SeekableByteChannel) Channel constructor} and more
+ * advanced instances through the {@link Builder}.
+ *
+ *
+ * @param The {@link SeekableByteChannel} type.
+ * @see FilterInputStream
+ * @see FilterOutputStream
+ * @see FilterReader
+ * @see FilterWritableByteChannel
+ * @see ProxyInputStream
+ * @see ProxyOutputStream
+ * @see ProxyReader
+ * @see ProxyWriter
+ * @since 2.22.0
+ */
+public class FilterSeekableByteChannel extends FilterByteChannel implements SeekableByteChannel {
+
+ /**
+ * Builds instances of {@link FilterSeekableByteChannel} for subclasses.
+ *
+ * @param The {@link FilterSeekableByteChannel} type.
+ * @param The {@link SeekableByteChannel} type wrapped by the FilterChannel.
+ * @param The builder type.
+ */
+ public abstract static class AbstractBuilder, C extends SeekableByteChannel, B extends AbstractBuilder>
+ extends FilterByteChannel.AbstractBuilder {
+
+ /**
+ * Constructs a new builder for {@link FilterSeekableByteChannel}.
+ */
+ public AbstractBuilder() {
+ // empty
+ }
+ }
+
+ /**
+ * Builds instances of {@link FilterSeekableByteChannel}.
+ */
+ public static class Builder extends AbstractBuilder, SeekableByteChannel, Builder> {
+
+ /**
+ * Builds instances of {@link FilterSeekableByteChannel}.
+ */
+ protected Builder() {
+ // empty
+ }
+
+ @Override
+ public FilterSeekableByteChannel get() throws IOException {
+ return new FilterSeekableByteChannel<>(this);
+ }
+ }
+
+ /**
+ * Creates a new {@link Builder}.
+ *
+ * @return A new {@link Builder}.
+ */
+ public static Builder forSeekableByteChannel() {
+ return new Builder();
+ }
+
+ FilterSeekableByteChannel(final Builder builder) throws IOException {
+ super(builder);
+ }
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param channel The channel to wrap.
+ */
+ public FilterSeekableByteChannel(final C channel) {
+ super(channel);
+ }
+
+ @Override
+ public long position() throws IOException {
+ return channel.position();
+ }
+
+ @Override
+ public SeekableByteChannel position(final long newPosition) throws IOException {
+ return channel.position(newPosition);
+ }
+
+ @Override
+ public long size() throws IOException {
+ return channel.size();
+ }
+
+ @Override
+ public SeekableByteChannel truncate(final long size) throws IOException {
+ return channel.truncate(size);
+ }
+}
diff --git a/src/main/java/org/apache/commons/io/channels/FilterWritableByteChannel.java b/src/main/java/org/apache/commons/io/channels/FilterWritableByteChannel.java
new file mode 100644
index 00000000000..ca3149aec38
--- /dev/null
+++ b/src/main/java/org/apache/commons/io/channels/FilterWritableByteChannel.java
@@ -0,0 +1,120 @@
+/*
+ * 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.io.channels;
+
+import java.io.FilterInputStream;
+import java.io.FilterOutputStream;
+import java.io.FilterReader;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.WritableByteChannel;
+
+import org.apache.commons.io.input.ProxyInputStream;
+import org.apache.commons.io.input.ProxyReader;
+import org.apache.commons.io.output.ProxyOutputStream;
+import org.apache.commons.io.output.ProxyWriter;
+
+/**
+ * A {@link WritableByteChannel} filter which delegates to the wrapped {@link WritableByteChannel}.
+ *
+ * A {@code FilterWritableByteChannel} wraps some other channel, which it uses as its basic source of data, possibly transforming the data along the way or
+ * providing additional functionality. The class {@code FilterWritableByteChannel} itself simply overrides methods of {@code WritableByteChannel} with versions
+ * that pass all requests to the wrapped channel. Subclasses of {@code FilterWritableByteChannel} may of course override any methods declared or inherited by
+ * {@code WritableByteChannel}, and may also provide additional fields and methods.
+ *
+ *
+ * You construct s simple instance with the {@link FilterWritableByteChannel#FilterWritableByteChannel(WritableByteChannel) Channel constructor} and more
+ * advanced instances through the {@link Builder}.
+ *
+ *
+ * @param The {@link WritableByteChannel} type.
+ * @see FilterInputStream
+ * @see FilterOutputStream
+ * @see FilterReader
+ * @see FilterWritableByteChannel
+ * @see ProxyInputStream
+ * @see ProxyOutputStream
+ * @see ProxyReader
+ * @see ProxyWriter
+ * @since 2.22.0
+ */
+public class FilterWritableByteChannel extends FilterChannel implements WritableByteChannel {
+
+ /**
+ * Builds instances of {@link FilterWritableByteChannel} for subclasses.
+ *
+ * @param The {@link FilterWritableByteChannel} type.
+ * @param The {@link WritableByteChannel} type wrapped by the FilterChannel.
+ * @param The builder type.
+ */
+ public abstract static class AbstractBuilder, C extends WritableByteChannel, B extends AbstractBuilder>
+ extends FilterChannel.AbstractBuilder {
+
+ /**
+ * Constructs a new builder for {@link FilterWritableByteChannel}.
+ */
+ public AbstractBuilder() {
+ // empty
+ }
+ }
+
+ /**
+ * Builds instances of {@link FilterByteChannel}.
+ */
+ public static class Builder extends AbstractBuilder, WritableByteChannel, Builder> {
+
+ /**
+ * Builds instances of {@link FilterByteChannel}.
+ */
+ protected Builder() {
+ // empty
+ }
+
+ @Override
+ public FilterWritableByteChannel get() throws IOException {
+ return new FilterWritableByteChannel<>(this);
+ }
+ }
+
+ /**
+ * Creates a new {@link Builder}.
+ *
+ * @return A new {@link Builder}.
+ */
+ public static Builder forWritableByteChannel() {
+ return new Builder();
+ }
+
+ FilterWritableByteChannel(final Builder builder) throws IOException {
+ super(builder);
+ }
+
+ /**
+ * Constructs a new instance.
+ *
+ * @param channel The channel to wrap.
+ */
+ public FilterWritableByteChannel(final C channel) {
+ super(channel);
+ }
+
+ @Override
+ public int write(final ByteBuffer src) throws IOException {
+ return channel.write(src);
+ }
+}
diff --git a/src/main/java/org/apache/commons/io/charset/CharsetDecoders.java b/src/main/java/org/apache/commons/io/charset/CharsetDecoders.java
index 8595be79e8a..11bd8b226df 100644
--- a/src/main/java/org/apache/commons/io/charset/CharsetDecoders.java
+++ b/src/main/java/org/apache/commons/io/charset/CharsetDecoders.java
@@ -30,11 +30,11 @@ public final class CharsetDecoders {
/**
* Returns the given non-null CharsetDecoder or a new default CharsetDecoder.
*
- * Null input maps to the virtual machine's {@link Charset#defaultCharset() default charset} decoder.
+ * Null input maps to the virtual machine's {@linkplain Charset#defaultCharset() default charset} decoder.
*
*
* @param charsetDecoder The CharsetDecoder to test.
- * @return the given non-null CharsetDecoder or a new default CharsetDecoder.
+ * @return The given non-null CharsetDecoder or a new default CharsetDecoder.
*/
public static CharsetDecoder toCharsetDecoder(final CharsetDecoder charsetDecoder) {
return charsetDecoder != null ? charsetDecoder : Charset.defaultCharset().newDecoder();
diff --git a/src/main/java/org/apache/commons/io/charset/CharsetEncoders.java b/src/main/java/org/apache/commons/io/charset/CharsetEncoders.java
index d0f9cd04be1..d5e1a00971d 100644
--- a/src/main/java/org/apache/commons/io/charset/CharsetEncoders.java
+++ b/src/main/java/org/apache/commons/io/charset/CharsetEncoders.java
@@ -31,11 +31,11 @@ public final class CharsetEncoders {
/**
* Returns the given non-null CharsetEncoder or a new default CharsetEncoder.
*
- * Null input maps to the virtual machine's {@link Charset#defaultCharset() default charset} decoder.
+ * Null input maps to the virtual machine's {@linkplain Charset#defaultCharset() default charset} decoder.
*
*
* @param charsetEncoder The CharsetEncoder to test.
- * @return the given non-null CharsetEncoder or a new default CharsetEncoder.
+ * @return The given non-null CharsetEncoder or a new default CharsetEncoder.
*/
public static CharsetEncoder toCharsetEncoder(final CharsetEncoder charsetEncoder) {
return toCharsetEncoder(charsetEncoder, () -> Charset.defaultCharset().newEncoder());
@@ -46,7 +46,7 @@ public static CharsetEncoder toCharsetEncoder(final CharsetEncoder charsetEncode
*
* @param charsetEncoder The CharsetEncoder to test.
* @param defaultSupplier The CharsetEncoder supplier to get when charsetEncoder is null.
- * @return the given non-null CharsetEncoder or a new default CharsetEncoder.
+ * @return The given non-null CharsetEncoder or a new default CharsetEncoder.
* @since 2.13.0
*/
public static CharsetEncoder toCharsetEncoder(final CharsetEncoder charsetEncoder, final Supplier defaultSupplier) {
diff --git a/src/main/java/org/apache/commons/io/comparator/CompositeFileComparator.java b/src/main/java/org/apache/commons/io/comparator/CompositeFileComparator.java
index 0934f895f7a..7600950e730 100644
--- a/src/main/java/org/apache/commons/io/comparator/CompositeFileComparator.java
+++ b/src/main/java/org/apache/commons/io/comparator/CompositeFileComparator.java
@@ -58,7 +58,7 @@ public class CompositeFileComparator extends AbstractFileComparator implements S
/**
* Constructs a composite comparator for the set of delegate comparators.
*
- * @param delegates The delegate file comparators
+ * @param delegates The delegate file comparators.
*/
public CompositeFileComparator(@SuppressWarnings("unchecked") final Comparator... delegates) {
this.delegates = delegates == null ? emptyArray() : delegates.clone();
@@ -67,7 +67,7 @@ public CompositeFileComparator(@SuppressWarnings("unchecked") final Comparator> delegates) {
this.delegates = delegates == null ? emptyArray()
@@ -77,9 +77,9 @@ public CompositeFileComparator(final Iterable> delegates) {
/**
* Compares the two files using delegate comparators.
*
- * @param file1 The first file to compare
- * @param file2 The second file to compare
- * @return the first non-zero result returned from the delegate comparators or zero.
+ * @param file1 The first file to compare.
+ * @param file2 The second file to compare.
+ * @return The first non-zero result returned from the delegate comparators or zero.
*/
@Override
public int compare(final File file1, final File file2) {
@@ -94,7 +94,7 @@ private Comparator[] emptyArray() {
/**
* String representation of this file comparator.
*
- * @return String representation of this file comparator
+ * @return String representation of this file comparator.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/comparator/DefaultFileComparator.java b/src/main/java/org/apache/commons/io/comparator/DefaultFileComparator.java
index c447f085198..76e8687373a 100644
--- a/src/main/java/org/apache/commons/io/comparator/DefaultFileComparator.java
+++ b/src/main/java/org/apache/commons/io/comparator/DefaultFileComparator.java
@@ -69,9 +69,9 @@ public DefaultFileComparator() {
/**
* Compares the two files using the {@link File#compareTo(File)} method.
*
- * @param file1 The first file to compare
- * @param file2 The second file to compare
- * @return the result of calling file1's
+ * @param file1 The first file to compare.
+ * @param file2 The second file to compare.
+ * @return The result of calling file1's
* {@link File#compareTo(File)} with file2 as the parameter.
*/
@Override
diff --git a/src/main/java/org/apache/commons/io/comparator/DirectoryFileComparator.java b/src/main/java/org/apache/commons/io/comparator/DirectoryFileComparator.java
index 038dffeda9d..ca0b1ea32ca 100644
--- a/src/main/java/org/apache/commons/io/comparator/DirectoryFileComparator.java
+++ b/src/main/java/org/apache/commons/io/comparator/DirectoryFileComparator.java
@@ -75,7 +75,7 @@ public DirectoryFileComparator() {
*
* @param file1 The first file to compare.
* @param file2 The second file to compare.
- * @return the result of calling file1's {@link File#compareTo(File)} with file2 as the parameter.
+ * @return The result of calling file1's {@link File#compareTo(File)} with file2 as the parameter.
*/
@Override
public int compare(final File file1, final File file2) {
diff --git a/src/main/java/org/apache/commons/io/comparator/ExtensionFileComparator.java b/src/main/java/org/apache/commons/io/comparator/ExtensionFileComparator.java
index 3b4e1e2e115..19d5618ca6d 100644
--- a/src/main/java/org/apache/commons/io/comparator/ExtensionFileComparator.java
+++ b/src/main/java/org/apache/commons/io/comparator/ExtensionFileComparator.java
@@ -93,7 +93,7 @@ public ExtensionFileComparator() {
/**
* Constructs a file extension comparator instance with the specified case-sensitivity.
*
- * @param ioCase how to handle case sensitivity, null means case-sensitive
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
*/
public ExtensionFileComparator(final IOCase ioCase) {
this.ioCase = IOCase.value(ioCase, IOCase.SENSITIVE);
@@ -102,9 +102,9 @@ public ExtensionFileComparator(final IOCase ioCase) {
/**
* Compares the extensions of two files the specified case sensitivity.
*
- * @param file1 The first file to compare
- * @param file2 The second file to compare
- * @return a negative value if the first file's extension
+ * @param file1 The first file to compare.
+ * @param file2 The second file to compare.
+ * @return A negative value if the first file's extension
* is less than the second, zero if the extensions are the
* same and a positive value if the first files extension
* is greater than the second file.
@@ -119,7 +119,7 @@ public int compare(final File file1, final File file2) {
/**
* String representation of this file comparator.
*
- * @return String representation of this file comparator
+ * @return String representation of this file comparator.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/comparator/LastModifiedFileComparator.java b/src/main/java/org/apache/commons/io/comparator/LastModifiedFileComparator.java
index da0794f2cf2..71e7a67d977 100644
--- a/src/main/java/org/apache/commons/io/comparator/LastModifiedFileComparator.java
+++ b/src/main/java/org/apache/commons/io/comparator/LastModifiedFileComparator.java
@@ -74,7 +74,7 @@ public LastModifiedFileComparator() {
*
* @param file1 The first file to compare.
* @param file2 The second file to compare.
- * @return a negative value if the first file's last modified date/time is less than the second, zero if the last
+ * @return A negative value if the first file's last modified date/time is less than the second, zero if the last
* modified date/time are the same and a positive value if the first files last modified date/time is
* greater than the second file.
*/
diff --git a/src/main/java/org/apache/commons/io/comparator/NameFileComparator.java b/src/main/java/org/apache/commons/io/comparator/NameFileComparator.java
index 41590fa6636..abb52636c64 100644
--- a/src/main/java/org/apache/commons/io/comparator/NameFileComparator.java
+++ b/src/main/java/org/apache/commons/io/comparator/NameFileComparator.java
@@ -89,7 +89,7 @@ public NameFileComparator() {
/**
* Constructs a file name comparator instance with the specified case-sensitivity.
*
- * @param ioCase how to handle case sensitivity, null means case-sensitive
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
*/
public NameFileComparator(final IOCase ioCase) {
this.ioCase = IOCase.value(ioCase, IOCase.SENSITIVE);
@@ -98,9 +98,9 @@ public NameFileComparator(final IOCase ioCase) {
/**
* Compares the names of two files with the specified case sensitivity.
*
- * @param file1 The first file to compare
- * @param file2 The second file to compare
- * @return a negative value if the first file's name
+ * @param file1 The first file to compare.
+ * @param file2 The second file to compare.
+ * @return A negative value if the first file's name
* is less than the second, zero if the names are the
* same and a positive value if the first files name
* is greater than the second file.
@@ -113,7 +113,7 @@ public int compare(final File file1, final File file2) {
/**
* String representation of this file comparator.
*
- * @return String representation of this file comparator
+ * @return String representation of this file comparator.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/comparator/PathFileComparator.java b/src/main/java/org/apache/commons/io/comparator/PathFileComparator.java
index 1f41eb74185..36faa411185 100644
--- a/src/main/java/org/apache/commons/io/comparator/PathFileComparator.java
+++ b/src/main/java/org/apache/commons/io/comparator/PathFileComparator.java
@@ -51,6 +51,7 @@
*
* Serialization is deprecated and will be removed in 3.0.
*
+ *
* @since 1.4
*/
public class PathFileComparator extends AbstractFileComparator implements Serializable {
@@ -88,7 +89,7 @@ public PathFileComparator() {
/**
* Constructs a file path comparator instance with the specified case-sensitivity.
*
- * @param ioCase how to handle case sensitivity, null means case-sensitive
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
*/
public PathFileComparator(final IOCase ioCase) {
this.ioCase = IOCase.value(ioCase, IOCase.SENSITIVE);
@@ -97,9 +98,9 @@ public PathFileComparator(final IOCase ioCase) {
/**
* Compares the paths of two files the specified case sensitivity.
*
- * @param file1 The first file to compare
- * @param file2 The second file to compare
- * @return a negative value if the first file's path
+ * @param file1 The first file to compare.
+ * @param file2 The second file to compare.
+ * @return A negative value if the first file's path
* is less than the second, zero if the paths are the
* same and a positive value if the first files path
* is greater than the second file.
@@ -112,7 +113,7 @@ public int compare(final File file1, final File file2) {
/**
* String representation of this file comparator.
*
- * @return String representation of this file comparator
+ * @return String representation of this file comparator.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/comparator/ReverseFileComparator.java b/src/main/java/org/apache/commons/io/comparator/ReverseFileComparator.java
index 82cfd16588a..c7516881645 100644
--- a/src/main/java/org/apache/commons/io/comparator/ReverseFileComparator.java
+++ b/src/main/java/org/apache/commons/io/comparator/ReverseFileComparator.java
@@ -49,7 +49,7 @@ final class ReverseFileComparator extends AbstractFileComparator implements Seri
*
* @param file1 The first file to compare.
* @param file2 The second file to compare.
- * @return the result from the delegate {@link Comparator#compare(Object, Object)} reversing the value,
+ * @return The result from the delegate {@link Comparator#compare(Object, Object)} reversing the value,
* positive becomes negative and vice versa.
*/
@Override
diff --git a/src/main/java/org/apache/commons/io/comparator/SizeFileComparator.java b/src/main/java/org/apache/commons/io/comparator/SizeFileComparator.java
index 5154d9b3256..9df6c7a5c06 100644
--- a/src/main/java/org/apache/commons/io/comparator/SizeFileComparator.java
+++ b/src/main/java/org/apache/commons/io/comparator/SizeFileComparator.java
@@ -107,9 +107,9 @@ public SizeFileComparator(final boolean sumDirectoryContents) {
/**
* Compares the length of two files.
*
- * @param file1 The first file to compare
- * @param file2 The second file to compare
- * @return a negative value if the first file's length
+ * @param file1 The first file to compare.
+ * @param file2 The second file to compare.
+ * @return A negative value if the first file's length
* is less than the second, zero if the lengths are the
* same and a positive value if the first files length
* is greater than the second file.
@@ -141,7 +141,7 @@ public int compare(final File file1, final File file2) {
/**
* String representation of this file comparator.
*
- * @return String representation of this file comparator
+ * @return String representation of this file comparator.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/doc-files/leaf.svg b/src/main/java/org/apache/commons/io/doc-files/leaf.svg
new file mode 100644
index 00000000000..71de588c648
--- /dev/null
+++ b/src/main/java/org/apache/commons/io/doc-files/leaf.svg
@@ -0,0 +1,45 @@
+
+
+
\ No newline at end of file
diff --git a/src/main/java/org/apache/commons/io/doc-files/logo.png b/src/main/java/org/apache/commons/io/doc-files/logo.png
new file mode 100644
index 00000000000..02a758f0ed8
Binary files /dev/null and b/src/main/java/org/apache/commons/io/doc-files/logo.png differ
diff --git a/src/main/java/org/apache/commons/io/file/AccumulatorPathVisitor.java b/src/main/java/org/apache/commons/io/file/AccumulatorPathVisitor.java
index 1551231cfaf..0819e2e510e 100644
--- a/src/main/java/org/apache/commons/io/file/AccumulatorPathVisitor.java
+++ b/src/main/java/org/apache/commons/io/file/AccumulatorPathVisitor.java
@@ -84,7 +84,7 @@ public AccumulatorPathVisitor get() {
/**
* Builds instances of {@link AccumulatorPathVisitor}.
*
- * @return a new builder.
+ * @return A new builder.
* @since 2.19.0
*/
public static Builder builder() {
@@ -94,7 +94,7 @@ public static Builder builder() {
/**
* Constructs a new instance configured with a BigInteger {@link PathCounters}.
*
- * @return a new instance configured with a BigInteger {@link PathCounters}.
+ * @return A new instance configured with a BigInteger {@link PathCounters}.
* @see #builder()
* @see Builder
*/
@@ -107,7 +107,7 @@ public static AccumulatorPathVisitor withBigIntegerCounters() {
*
* @param fileFilter Filters files to accumulate and count.
* @param dirFilter Filters directories to accumulate and count.
- * @return a new instance configured with a long {@link PathCounters}.
+ * @return A new instance configured with a long {@link PathCounters}.
* @see #builder()
* @see Builder
* @since 2.9.0
@@ -119,7 +119,7 @@ public static AccumulatorPathVisitor withBigIntegerCounters(final PathFilter fil
/**
* Constructs a new instance configured with a long {@link PathCounters}.
*
- * @return a new instance configured with a long {@link PathCounters}.
+ * @return A new instance configured with a long {@link PathCounters}.
* @see #builder()
* @see Builder
*/
@@ -132,7 +132,7 @@ public static AccumulatorPathVisitor withLongCounters() {
*
* @param fileFilter Filters files to accumulate and count.
* @param dirFilter Filters directories to accumulate and count.
- * @return a new instance configured with a long {@link PathCounters}.
+ * @return A new instance configured with a long {@link PathCounters}.
* @see #builder()
* @see Builder
* @since 2.9.0
@@ -195,7 +195,6 @@ public AccumulatorPathVisitor(final PathCounters pathCounter, final PathFilter f
* @since 2.12.0
* @deprecated Use {@link #builder()}.
*/
- @SuppressWarnings("deprecation")
@Deprecated
public AccumulatorPathVisitor(final PathCounters pathCounter, final PathFilter fileFilter, final PathFilter dirFilter,
final IOBiFunction visitFileFailed) {
@@ -224,7 +223,7 @@ public boolean equals(final Object obj) {
/**
* Gets a copy of the list of visited directories.
*
- * @return a copy of the list of visited directories.
+ * @return A copy of the list of visited directories.
*/
public List getDirList() {
return new ArrayList<>(dirList);
@@ -233,7 +232,7 @@ public List getDirList() {
/**
* Gets a copy of the list of visited files.
*
- * @return a copy of the list of visited files.
+ * @return A copy of the list of visited files.
*/
public List getFileList() {
return new ArrayList<>(fileList);
@@ -251,10 +250,10 @@ public int hashCode() {
* Relativizes each directory path with {@link Path#relativize(Path)} against the given {@code parent}, optionally
* sorting the result.
*
- * @param parent A parent path
- * @param sort Whether to sort
+ * @param parent A parent path.
+ * @param sort Whether to sort.
* @param comparator How to sort, null uses default sorting.
- * @return A new list
+ * @return A new list.
*/
public List relativizeDirectories(final Path parent, final boolean sort,
final Comparator super Path> comparator) {
@@ -265,10 +264,10 @@ public List relativizeDirectories(final Path parent, final boolean sort,
* Relativizes each file path with {@link Path#relativize(Path)} against the given {@code parent}, optionally
* sorting the result.
*
- * @param parent A parent path
- * @param sort Whether to sort
+ * @param parent A parent path.
+ * @param sort Whether to sort.
* @param comparator How to sort, null uses default sorting.
- * @return A new list
+ * @return A new list.
*/
public List relativizeFiles(final Path parent, final boolean sort,
final Comparator super Path> comparator) {
diff --git a/src/main/java/org/apache/commons/io/file/CleaningPathVisitor.java b/src/main/java/org/apache/commons/io/file/CleaningPathVisitor.java
index 2b06547809b..8623bc01b86 100644
--- a/src/main/java/org/apache/commons/io/file/CleaningPathVisitor.java
+++ b/src/main/java/org/apache/commons/io/file/CleaningPathVisitor.java
@@ -38,7 +38,7 @@ public class CleaningPathVisitor extends CountingPathVisitor {
/**
* Constructs a new instance configured with a BigInteger {@link PathCounters}.
*
- * @return a new instance configured with a BigInteger {@link PathCounters}.
+ * @return A new instance configured with a BigInteger {@link PathCounters}.
*/
public static CountingPathVisitor withBigIntegerCounters() {
return new CleaningPathVisitor(Counters.bigIntegerPathCounters());
@@ -47,7 +47,7 @@ public static CountingPathVisitor withBigIntegerCounters() {
/**
* Constructs a new instance configured with a long {@link PathCounters}.
*
- * @return a new instance configured with a long {@link PathCounters}.
+ * @return A new instance configured with a long {@link PathCounters}.
*/
public static CountingPathVisitor withLongCounters() {
return new CleaningPathVisitor(Counters.longPathCounters());
@@ -85,7 +85,7 @@ public CleaningPathVisitor(final PathCounters pathCounter, final String... skip)
/**
* Returns true to process the given path, false if not.
*
- * @param path the path to test.
+ * @param path The path to test.
* @return true to process the given path, false if not.
*/
private boolean accept(final Path path) {
diff --git a/src/main/java/org/apache/commons/io/file/CopyDirectoryVisitor.java b/src/main/java/org/apache/commons/io/file/CopyDirectoryVisitor.java
index 7172b2d0671..2ef49e85241 100644
--- a/src/main/java/org/apache/commons/io/file/CopyDirectoryVisitor.java
+++ b/src/main/java/org/apache/commons/io/file/CopyDirectoryVisitor.java
@@ -48,8 +48,8 @@ private static CopyOption[] toCopyOption(final CopyOption... copyOptions) {
* Constructs an instance that copies all files.
*
* @param pathCounter How to count visits.
- * @param sourceDirectory The source directory
- * @param targetDirectory The target directory
+ * @param sourceDirectory The source directory.
+ * @param targetDirectory The target directory.
* @param copyOptions Specifies how the copying should be done.
*/
public CopyDirectoryVisitor(final PathCounters pathCounter, final Path sourceDirectory, final Path targetDirectory, final CopyOption... copyOptions) {
@@ -65,8 +65,8 @@ public CopyDirectoryVisitor(final PathCounters pathCounter, final Path sourceDir
* @param pathCounter How to count visits.
* @param fileFilter How to filter file paths.
* @param dirFilter How to filter directory paths.
- * @param sourceDirectory The source directory
- * @param targetDirectory The target directory
+ * @param sourceDirectory The source directory.
+ * @param targetDirectory The target directory.
* @param copyOptions Specifies how the copying should be done.
* @since 2.9.0
*/
@@ -81,8 +81,8 @@ public CopyDirectoryVisitor(final PathCounters pathCounter, final PathFilter fil
/**
* Copies the sourceFile to the targetFile.
*
- * @param sourceFile the source file.
- * @param targetFile the target file.
+ * @param sourceFile The source file.
+ * @param targetFile The target file.
* @throws IOException if an I/O error occurs.
* @since 2.8.0
*/
@@ -109,7 +109,7 @@ public boolean equals(final Object obj) {
/**
* Gets the copy options.
*
- * @return the copy options.
+ * @return The copy options.
* @since 2.8.0
*/
public CopyOption[] getCopyOptions() {
@@ -119,7 +119,7 @@ public CopyOption[] getCopyOptions() {
/**
* Gets the source directory.
*
- * @return the source directory.
+ * @return The source directory.
* @since 2.8.0
*/
public Path getSourceDirectory() {
@@ -129,7 +129,7 @@ public Path getSourceDirectory() {
/**
* Gets the target directory.
*
- * @return the target directory.
+ * @return The target directory.
* @since 2.8.0
*/
public Path getTargetDirectory() {
@@ -161,8 +161,8 @@ public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAt
* {@link ProviderMismatchException}. Special care is taken to handle differences in file system separators.
*
*
- * @param directory the directory to relativize.
- * @return a new path, relativized against sourceDirectory, then resolved against targetDirectory.
+ * @param directory The directory to relativize.
+ * @return A new path, relativized against sourceDirectory, then resolved against targetDirectory.
*/
private Path resolveRelativeAsString(final Path directory) {
return PathUtils.resolve(targetDirectory, sourceDirectory.relativize(directory));
diff --git a/src/main/java/org/apache/commons/io/file/Counters.java b/src/main/java/org/apache/commons/io/file/Counters.java
index b1abd721d9c..16b01740987 100644
--- a/src/main/java/org/apache/commons/io/file/Counters.java
+++ b/src/main/java/org/apache/commons/io/file/Counters.java
@@ -39,9 +39,9 @@ private static class AbstractPathCounters implements PathCounters {
/**
* Constructs a new instance.
*
- * @param byteCounter the byte counter.
- * @param directoryCounter the directory counter.
- * @param fileCounter the file counter.
+ * @param byteCounter The byte counter.
+ * @param directoryCounter The directory counter.
+ * @param fileCounter The file counter.
*/
protected AbstractPathCounters(final Counter byteCounter, final Counter directoryCounter, final Counter fileCounter) {
this.byteCounter = byteCounter;
@@ -76,7 +76,7 @@ public Counter getDirectoryCounter() {
/**
* Gets the count of visited files.
*
- * @return the byte count of visited files.
+ * @return The byte count of visited files.
*/
@Override
public Counter getFileCounter() {
@@ -186,28 +186,28 @@ public interface Counter {
/**
* Adds the given number to this counter.
*
- * @param val the value to add.
+ * @param val The value to add.
*/
void add(long val);
/**
* Gets the counter as a long.
*
- * @return the counter as a long.
+ * @return The counter as a long.
*/
long get();
/**
* Gets the counter as a BigInteger.
*
- * @return the counter as a BigInteger.
+ * @return The counter as a BigInteger.
*/
BigInteger getBigInteger();
/**
* Gets the counter as a Long.
*
- * @return the counter as a Long.
+ * @return The counter as a Long.
*/
Long getLong();
@@ -369,21 +369,21 @@ public interface PathCounters {
/**
* Gets the byte counter.
*
- * @return the byte counter.
+ * @return The byte counter.
*/
Counter getByteCounter();
/**
* Gets the directory counter.
*
- * @return the directory counter.
+ * @return The directory counter.
*/
Counter getDirectoryCounter();
/**
* Gets the file counter.
*
- * @return the file counter.
+ * @return The file counter.
*/
Counter getFileCounter();
@@ -399,7 +399,7 @@ default void reset() {
/**
* Returns a new BigInteger Counter.
*
- * @return a new BigInteger Counter.
+ * @return A new BigInteger Counter.
*/
public static Counter bigIntegerCounter() {
return new BigIntegerCounter();
@@ -408,7 +408,7 @@ public static Counter bigIntegerCounter() {
/**
* Returns a new BigInteger PathCounters.
*
- * @return a new BigInteger PathCounters.
+ * @return A new BigInteger PathCounters.
*/
public static PathCounters bigIntegerPathCounters() {
return new BigIntegerPathCounters();
@@ -417,7 +417,7 @@ public static PathCounters bigIntegerPathCounters() {
/**
* Returns a new long Counter.
*
- * @return a new long Counter.
+ * @return A new long Counter.
*/
public static Counter longCounter() {
return new LongCounter();
@@ -426,7 +426,7 @@ public static Counter longCounter() {
/**
* Returns a new BigInteger PathCounters.
*
- * @return a new BigInteger PathCounters.
+ * @return A new BigInteger PathCounters.
*/
public static PathCounters longPathCounters() {
return new LongPathCounters();
@@ -435,7 +435,7 @@ public static PathCounters longPathCounters() {
/**
* Returns the no-op Counter.
*
- * @return the no-op Counter.
+ * @return The no-op Counter.
* @since 2.9.0
*/
public static Counter noopCounter() {
@@ -445,7 +445,7 @@ public static Counter noopCounter() {
/**
* Returns the no-op PathCounters.
*
- * @return the no-op PathCounters.
+ * @return The no-op PathCounters.
* @since 2.9.0
*/
public static PathCounters noopPathCounters() {
@@ -455,7 +455,7 @@ public static PathCounters noopPathCounters() {
/**
* Construct a new instance.
*
- * @deprecated Will be private in 4.0
+ * @deprecated Will be private in 3.0.
*/
@Deprecated
public Counters() {
diff --git a/src/main/java/org/apache/commons/io/file/CountingPathVisitor.java b/src/main/java/org/apache/commons/io/file/CountingPathVisitor.java
index ab02ad073e2..20d297d531e 100644
--- a/src/main/java/org/apache/commons/io/file/CountingPathVisitor.java
+++ b/src/main/java/org/apache/commons/io/file/CountingPathVisitor.java
@@ -28,7 +28,6 @@
import org.apache.commons.io.file.Counters.PathCounters;
import org.apache.commons.io.filefilter.IOFileFilter;
-import org.apache.commons.io.filefilter.SymbolicLinkFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.function.IOBiFunction;
@@ -152,7 +151,7 @@ static UnaryOperator defaultDirectoryTransformer() {
}
static IOFileFilter defaultFileFilter() {
- return new SymbolicLinkFileFilter(FileVisitResult.TERMINATE, FileVisitResult.CONTINUE);
+ return TrueFileFilter.INSTANCE;
}
static PathCounters defaultPathCounters() {
@@ -162,7 +161,7 @@ static PathCounters defaultPathCounters() {
/**
* Constructs a new instance configured with a {@link BigInteger} {@link PathCounters}.
*
- * @return a new instance configured with a {@link BigInteger} {@link PathCounters}.
+ * @return A new instance configured with a {@link BigInteger} {@link PathCounters}.
*/
public static CountingPathVisitor withBigIntegerCounters() {
return new Builder().setPathCounters(Counters.bigIntegerPathCounters()).get();
@@ -171,7 +170,7 @@ public static CountingPathVisitor withBigIntegerCounters() {
/**
* Constructs a new instance configured with a {@code long} {@link PathCounters}.
*
- * @return a new instance configured with a {@code long} {@link PathCounters}.
+ * @return A new instance configured with a {@code long} {@link PathCounters}.
*/
public static CountingPathVisitor withLongCounters() {
return new Builder().setPathCounters(Counters.longPathCounters()).get();
@@ -239,8 +238,8 @@ public CountingPathVisitor(final PathCounters pathCounters, final PathFilter fil
/**
* Tests whether the given file is accepted by the file filter.
*
- * @param file the visited file.
- * @param attributes the visited file attributes.
+ * @param file The visited file.
+ * @param attributes The visited file attributes.
* @return true to copy the given file, false if not.
* @since 2.20.0
*/
@@ -264,7 +263,7 @@ public boolean equals(final Object obj) {
/**
* Gets the visitation counts.
*
- * @return the visitation counts.
+ * @return The visitation counts.
*/
public PathCounters getPathCounters() {
return pathCounters;
@@ -295,7 +294,7 @@ public String toString() {
/**
* Updates the counter for visiting the given directory.
*
- * @param dir the visited directory.
+ * @param dir The visited directory.
* @param exc Encountered exception.
* @since 2.9.0
*/
@@ -306,8 +305,8 @@ protected void updateDirCounter(final Path dir, final IOException exc) {
/**
* Updates the counters for visiting the given file.
*
- * @param file the visited file.
- * @param attributes the visited file attributes.
+ * @param file The visited file.
+ * @param attributes The visited file attributes.
*/
protected void updateFileCounters(final Path file, final BasicFileAttributes attributes) {
pathCounters.getFileCounter().increment();
diff --git a/src/main/java/org/apache/commons/io/file/DeletingPathVisitor.java b/src/main/java/org/apache/commons/io/file/DeletingPathVisitor.java
index 7d460d88801..872475519ec 100644
--- a/src/main/java/org/apache/commons/io/file/DeletingPathVisitor.java
+++ b/src/main/java/org/apache/commons/io/file/DeletingPathVisitor.java
@@ -39,7 +39,7 @@ public class DeletingPathVisitor extends CountingPathVisitor {
/**
* Constructs a new instance configured with a BigInteger {@link PathCounters}.
*
- * @return a new instance configured with a BigInteger {@link PathCounters}.
+ * @return A new instance configured with a BigInteger {@link PathCounters}.
*/
public static DeletingPathVisitor withBigIntegerCounters() {
return new DeletingPathVisitor(Counters.bigIntegerPathCounters());
@@ -48,7 +48,7 @@ public static DeletingPathVisitor withBigIntegerCounters() {
/**
* Constructs a new instance configured with a long {@link PathCounters}.
*
- * @return a new instance configured with a long {@link PathCounters}.
+ * @return A new instance configured with a long {@link PathCounters}.
*/
public static DeletingPathVisitor withLongCounters() {
return new DeletingPathVisitor(Counters.longPathCounters());
@@ -102,7 +102,7 @@ public DeletingPathVisitor(final PathCounters pathCounter, final String... skip)
/**
* Returns true to process the given path, false if not.
*
- * @param path the path to test.
+ * @param path The path to test.
* @return true to process the given path, false if not.
*/
private boolean accept(final Path path) {
diff --git a/src/main/java/org/apache/commons/io/file/DirectoryStreamFilter.java b/src/main/java/org/apache/commons/io/file/DirectoryStreamFilter.java
index 9599eda84b6..2bba4edf6e1 100644
--- a/src/main/java/org/apache/commons/io/file/DirectoryStreamFilter.java
+++ b/src/main/java/org/apache/commons/io/file/DirectoryStreamFilter.java
@@ -54,7 +54,7 @@ public boolean accept(final Path path) throws IOException {
/**
* Gets the path filter.
*
- * @return the path filter.
+ * @return The path filter.
*/
public PathFilter getPathFilter() {
return pathFilter;
diff --git a/src/main/java/org/apache/commons/io/file/PathFilter.java b/src/main/java/org/apache/commons/io/file/PathFilter.java
index dbeef906261..a1a2989fcb3 100644
--- a/src/main/java/org/apache/commons/io/file/PathFilter.java
+++ b/src/main/java/org/apache/commons/io/file/PathFilter.java
@@ -33,8 +33,8 @@ public interface PathFilter {
* Tests whether or not to include the specified Path in a result.
*
* @param path The Path to test.
- * @param attributes the path's basic attributes (may be null).
- * @return a FileVisitResult
+ * @param attributes The path's basic attributes (may be null).
+ * @return A FileVisitResult.
*/
FileVisitResult accept(Path path, BasicFileAttributes attributes);
}
diff --git a/src/main/java/org/apache/commons/io/file/PathUtils.java b/src/main/java/org/apache/commons/io/file/PathUtils.java
index 055bbe06a0b..f18af5eff21 100644
--- a/src/main/java/org/apache/commons/io/file/PathUtils.java
+++ b/src/main/java/org/apache/commons/io/file/PathUtils.java
@@ -18,6 +18,7 @@
package org.apache.commons.io.file;
import java.io.File;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -75,6 +76,7 @@
import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IORandomAccessFile;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.RandomAccessFileMode;
import org.apache.commons.io.RandomAccessFiles;
@@ -100,8 +102,8 @@ private static final class RelativeSortedPaths {
/**
* Compares lists of paths regardless of their file systems.
*
- * @param list1 the first list.
- * @param list2 the second list.
+ * @param list1 The first list.
+ * @param list2 The second list.
* @return whether the lists are equal.
*/
private static boolean equalsIgnoreFileSystem(final List list1, final List list2) {
@@ -137,9 +139,15 @@ private static boolean equalsIgnoreFileSystem(final Path path1, final Path path2
return extractKey(separator1, string1).equals(extractKey(separator2, string2));
}
+ /**
+ * Replaces the file separator in a path string with a string that is not legal in a path on Windows, Linux, and macOS.
+ *
+ * @param separator The file separator.
+ * @param string A path.
+ * @return A key.
+ */
static String extractKey(final String separator, final String string) {
- // Replace the file separator in a path string with a string that is not legal in a path on Windows, Linux, and macOS.
- return string.replaceAll("\\" + separator, ">");
+ return string.replace(separator, ">");
}
final boolean equals;
@@ -200,32 +208,38 @@ private RelativeSortedPaths(final Path dir1, final Path dir2, final int maxDepth
private static final OpenOption[] OPEN_OPTIONS_TRUNCATE = { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING };
private static final OpenOption[] OPEN_OPTIONS_APPEND = { StandardOpenOption.CREATE, StandardOpenOption.APPEND };
+
/**
* Empty {@link CopyOption} array.
*
* @since 2.8.0
*/
public static final CopyOption[] EMPTY_COPY_OPTIONS = {};
+
/**
* Empty {@link DeleteOption} array.
*
* @since 2.8.0
*/
public static final DeleteOption[] EMPTY_DELETE_OPTION_ARRAY = {};
+
/**
* Empty {@link FileAttribute} array.
*
* @since 2.13.0
*/
public static final FileAttribute>[] EMPTY_FILE_ATTRIBUTE_ARRAY = {};
+
/**
* Empty {@link FileVisitOption} array.
*/
public static final FileVisitOption[] EMPTY_FILE_VISIT_OPTION_ARRAY = {};
+
/**
* Empty {@link LinkOption} array.
*/
public static final LinkOption[] EMPTY_LINK_OPTION_ARRAY = {};
+
/**
* {@link LinkOption} array for {@link LinkOption#NOFOLLOW_LINKS}.
*
@@ -234,16 +248,19 @@ private RelativeSortedPaths(final Path dir1, final Path dir2, final int maxDepth
*/
@Deprecated
public static final LinkOption[] NOFOLLOW_LINK_OPTION_ARRAY = { LinkOption.NOFOLLOW_LINKS };
+
/**
* A LinkOption used to follow link in this class, the inverse of {@link LinkOption#NOFOLLOW_LINKS}.
*
* @since 2.12.0
*/
static final LinkOption NULL_LINK_OPTION = null;
+
/**
* Empty {@link OpenOption} array.
*/
public static final OpenOption[] EMPTY_OPEN_OPTION_ARRAY = {};
+
/**
* Empty {@link Path} array.
*
@@ -266,7 +283,10 @@ private static AccumulatorPathVisitor accumulate(final Path directory, final int
}
/**
- * Cleans a directory by only deleting files, including in subdirectories, but without deleting the directories.
+ * Cleans a directory by only deleting files, including in subdirectories, without deleting directories.
+ *
+ * This leaves a directory empty of files but the directory and any subdirectories remain.
+ *
*
* @param directory directory to clean.
* @return The visitation path counters.
@@ -277,7 +297,10 @@ public static PathCounters cleanDirectory(final Path directory) throws IOExcepti
}
/**
- * Cleans a directory by only deleting files, including in subdirectories, but without deleting the directories.
+ * Cleans a directory by only deleting files, including in subdirectories, without deleting directories.
+ *
+ * This leaves a directory empty of files but the directory and any subdirectories remain.
+ *
*
* @param directory directory to clean.
* @param deleteOptions How to handle deletion.
@@ -289,11 +312,38 @@ public static PathCounters cleanDirectory(final Path directory, final DeleteOpti
return visitFileTree(new CleaningPathVisitor(Counters.longPathCounters(), deleteOptions), directory).getPathCounters();
}
+ /**
+ * Clears the contents at an existing Path by filling it with NUL ({@code 0)} bytes.
+ *
+ * @param path The target path to an existing file.
+ * @return The given path.
+ * @throws FileNotFoundException See {@link IORandomAccessFile#IORandomAccessFile(File, String)}.
+ * @throws IOException Thrown writing to the Path.
+ * @since 2.23.0
+ */
+ public static Path clear(final Path path) throws IOException {
+ RandomAccessFileMode.READ_WRITE.accept(path, IORandomAccessFile::clear);
+ return path;
+ }
+
+ /**
+ * Clears the contents at a Path by filling it with NUL ({@code 0)} bytes.
+ *
+ * @param path The target path, may not exist, may be null.
+ * @return The given path.
+ * @throws FileNotFoundException See {@link IORandomAccessFile#IORandomAccessFile(File, String)}.
+ * @throws IOException Thrown writing to the Path.
+ * @since 2.23.0
+ */
+ public static Path clearIfExists(final Path path) throws IOException {
+ return exists(path) ? clear(path) : path;
+ }
+
/**
* Compares the given {@link Path}'s last modified time to the given file time.
*
- * @param file the {@link Path} to test.
- * @param fileTime the time reference.
+ * @param file The {@link Path} to test.
+ * @param fileTime The time reference.
* @param options options indicating how to handle symbolic links.
* @return See {@link FileTime#compareTo(FileTime)}
* @throws IOException if an I/O error occurs.
@@ -378,7 +428,7 @@ public static PathCounters copyDirectory(final Path sourceDirectory, final Path
* @param sourceFile The source URL.
* @param targetFile The target file.
* @param copyOptions Specifies how the copying should be done.
- * @return The target file
+ * @return The target file.
* @throws IOException if an I/O error occurs.
* @see Files#copy(InputStream, Path, CopyOption...)
*/
@@ -393,7 +443,7 @@ public static Path copyFile(final URL sourceFile, final Path targetFile, final C
* @param sourceFile The source file.
* @param targetDirectory The target directory.
* @param copyOptions Specifies how the copying should be done.
- * @return The target file
+ * @return The target file.
* @throws IOException if an I/O error occurs.
* @see Files#copy(Path, Path, CopyOption...)
*/
@@ -410,7 +460,7 @@ public static Path copyFileToDirectory(final Path sourceFile, final Path targetD
* @param sourceFile The source URL.
* @param targetDirectory The target directory.
* @param copyOptions Specifies how the copying should be done.
- * @return The target file
+ * @return The target file.
* @throws IOException if an I/O error occurs.
* @see Files#copy(InputStream, Path, CopyOption...)
*/
@@ -485,7 +535,7 @@ public static Path createParentDirectories(final Path path, final LinkOption lin
/**
* Gets the current directory.
*
- * @return the current directory.
+ * @return The current directory.
* @since 2.9.0
*/
public static Path current() {
@@ -499,7 +549,7 @@ public static Path current() {
*
*
*
A directory to delete does not have to be empty.
- *
You get exceptions when a file or directory cannot be deleted; {@link File#delete()} returns a boolean.
+ *
You get exceptions when a file or directory cannot be deleted; {@link File#delete()} returns a boolean.
*
*
* @param path file or directory to delete, must not be {@code null}
@@ -518,7 +568,7 @@ public static PathCounters delete(final Path path) throws IOException {
*
*
*
A directory to delete does not have to be empty.
- *
You get exceptions when a file or directory cannot be deleted; {@link File#delete()} returns a boolean.
+ *
You get exceptions when a file or directory cannot be deleted; {@link File#delete()} returns a boolean.
*
*
* @param path file or directory to delete, must not be {@code null}
@@ -540,7 +590,7 @@ public static PathCounters delete(final Path path, final DeleteOption... deleteO
*
*
*
A directory to delete does not have to be empty.
- *
You get exceptions when a file or directory cannot be deleted; {@link File#delete()} returns a boolean.
+ *
You get exceptions when a file or directory cannot be deleted; {@link File#delete()} returns a boolean.
*
*
* @param path file or directory to delete, must not be {@code null}
@@ -603,7 +653,7 @@ public static PathCounters deleteDirectory(final Path directory, final LinkOptio
* @param file The file to delete.
* @return A visitor with path counts set to 1 file, 0 directories, and the size of the deleted file.
* @throws IOException if an I/O error occurs.
- * @throws NoSuchFileException if the file is a directory
+ * @throws NoSuchFileException if the file is a directory.
*/
public static PathCounters deleteFile(final Path file) throws IOException {
return deleteFile(file, EMPTY_DELETE_OPTION_ARRAY);
@@ -677,10 +727,22 @@ public static PathCounters deleteFile(final Path file, final LinkOption[] linkOp
return pathCounts;
}
+ /**
+ * A null-safe version of {@link Files#deleteIfExists(Path)}.
+ *
+ * @param path The path to the file to delete, may be {@code null}.
+ * @return Same as {@link Files#deleteIfExists(Path)} if {@code path} is non-null, false otherwise.
+ * @throws IOException Same as {@link Files#deleteIfExists(Path)}.
+ * @since 2.23.0
+ */
+ public static boolean deleteIfExists(final Path path) throws IOException {
+ return path != null && Files.deleteIfExists(path);
+ }
+
/**
* Delegates to {@link File#deleteOnExit()}.
*
- * @param path the path to delete.
+ * @param path The path to delete.
* @since 3.13.0
*/
public static void deleteOnExit(final Path path) {
@@ -771,7 +833,7 @@ public static boolean directoryContentEquals(final Path path1, final Path path2)
* @param path2 The second directory.
* @param maxDepth See {@link Files#walkFileTree(Path,Set,int,FileVisitor)}.
* @param linkOptions options to follow links.
- * @param fileVisitOptions options to configure the traversal
+ * @param fileVisitOptions options to configure the traversal.
* @return Whether the two directories contain the same files without considering file contents.
* @throws IOException if an I/O error is thrown by a visitor method.
*/
@@ -790,8 +852,8 @@ private static boolean exists(final Path path, final LinkOption... options) {
* File content is accessed through {@link Files#newInputStream(Path,OpenOption...)}.
*
*
- * @param path1 the first file path.
- * @param path2 the second file path.
+ * @param path1 The first file path.
+ * @param path2 The second file path.
* @return true if the content of the streams are equal or they both don't exist, false otherwise.
* @throws NullPointerException if either input is null.
* @throws IOException if an I/O error occurs.
@@ -807,8 +869,8 @@ public static boolean fileContentEquals(final Path path1, final Path path2) thro
* File content is accessed through {@link RandomAccessFileMode#create(Path)}.
*
*
- * @param path1 the first file path.
- * @param path2 the second file path.
+ * @param path1 The first file path.
+ * @param path2 The second file path.
* @param linkOptions options specifying how files are followed.
* @param openOptions ignored.
* @return true if the content of the streams are equal or they both don't exist, false otherwise.
@@ -883,9 +945,9 @@ public static boolean fileContentEquals(final Path path1, final Path path2, fina
* FileFilterUtils.suffixFileFilter(".java"));
*
* Example, showing how to print out a list of the
* current directory's executable files:
@@ -77,7 +77,7 @@ protected CanExecuteFileFilter() {
/**
* Tests to see if the file can be executed.
*
- * @param file the File to check.
+ * @param file The File to check.
* @return {@code true} if the file can be executed, otherwise {@code false}.
*/
@Override
@@ -88,8 +88,8 @@ public boolean accept(final File file) {
/**
* Tests to see if the file can be executed.
*
- * @param file the File to check.
- * @param attributes the path's basic attributes (may be null).
+ * @param file The File to check.
+ * @param attributes The path's basic attributes (may be null).
* @return {@code true} if the file can be executed, otherwise {@code false}.
* @since 2.9.0
*/
diff --git a/src/main/java/org/apache/commons/io/filefilter/CanReadFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/CanReadFileFilter.java
index da376e0f4f5..2d378e334f6 100644
--- a/src/main/java/org/apache/commons/io/filefilter/CanReadFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/CanReadFileFilter.java
@@ -24,7 +24,7 @@
import java.nio.file.attribute.BasicFileAttributes;
/**
- * This filter accepts {@link File}s that can be read.
+ * This filter accepts {@link File}s that are readable.
*
* Example, showing how to print out a list of the current directory's readable files:
*
@@ -87,7 +87,7 @@ protected CanReadFileFilter() {
/**
* Tests to see if the file can be read.
*
- * @param file the File to check.
+ * @param file The File to check.
* @return {@code true} if the file can be read, otherwise {@code false}.
*/
@Override
@@ -98,8 +98,8 @@ public boolean accept(final File file) {
/**
* Tests to see if the file can be read.
*
- * @param file the File to check.
- * @param attributes the path's basic attributes (may be null).
+ * @param file The File to check.
+ * @param attributes The path's basic attributes (may be null).
* @return {@code true} if the file can be read, otherwise {@code false}.
* @since 2.9.0
*/
diff --git a/src/main/java/org/apache/commons/io/filefilter/CanWriteFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/CanWriteFileFilter.java
index 899481c6465..50230c95324 100644
--- a/src/main/java/org/apache/commons/io/filefilter/CanWriteFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/CanWriteFileFilter.java
@@ -24,7 +24,7 @@
import java.nio.file.attribute.BasicFileAttributes;
/**
- * This filter accepts {@link File}s that can be written to.
+ * This filter accepts {@link File}s that are writable.
*
* Example, showing how to print out a list of the current directory's writable files:
*
@@ -54,6 +54,7 @@
* Serialization is deprecated and will be removed in 3.0.
*
*
+ * @see Files#isWritable(Path)
* @since 1.3
*/
public class CanWriteFileFilter extends AbstractFileFilter implements Serializable {
@@ -75,7 +76,7 @@ protected CanWriteFileFilter() {
/**
* Tests to see if the file can be written to.
*
- * @param file the File to check
+ * @param file The File to check.
* @return {@code true} if the file can be written to, otherwise {@code false}.
*/
@Override
@@ -86,8 +87,8 @@ public boolean accept(final File file) {
/**
* Tests to see if the file can be written to.
*
- * @param file the File to check
- * @param attributes the path's basic attributes (may be null).
+ * @param file The File to check.
+ * @param attributes The path's basic attributes (may be null).
* @return {@code true} if the file can be written to, otherwise {@code false}.
* @since 2.9.0
*/
diff --git a/src/main/java/org/apache/commons/io/filefilter/ConditionalFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/ConditionalFileFilter.java
index d59996a0461..c60a3d99070 100644
--- a/src/main/java/org/apache/commons/io/filefilter/ConditionalFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/ConditionalFileFilter.java
@@ -29,7 +29,7 @@ public interface ConditionalFileFilter {
* Adds the specified file filter to the list of file filters at the end of
* the list.
*
- * @param ioFileFilter the filter to be added
+ * @param ioFileFilter The filter to be added.
* @since 1.1
*/
void addFileFilter(IOFileFilter ioFileFilter);
@@ -37,7 +37,7 @@ public interface ConditionalFileFilter {
/**
* Gets this conditional file filter's list of file filters.
*
- * @return the file filter list
+ * @return The file filter list.
* @since 1.1
*/
List getFileFilters();
@@ -45,9 +45,9 @@ public interface ConditionalFileFilter {
/**
* Removes the specified file filter.
*
- * @param ioFileFilter filter to be removed
+ * @param ioFileFilter filter to be removed.
* @return {@code true} if the filter was found in the list,
- * {@code false} otherwise
+ * {@code false} otherwise.
* @since 1.1
*/
boolean removeFileFilter(IOFileFilter ioFileFilter);
@@ -56,7 +56,7 @@ public interface ConditionalFileFilter {
* Sets the list of file filters, replacing any previously configured
* file filters on this filter.
*
- * @param fileFilters the list of filters
+ * @param fileFilters The list of filters.
* @since 1.1
*/
void setFileFilters(List fileFilters);
diff --git a/src/main/java/org/apache/commons/io/filefilter/DelegateFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/DelegateFileFilter.java
index 4137644ca1d..03f96b2cd7f 100644
--- a/src/main/java/org/apache/commons/io/filefilter/DelegateFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/DelegateFileFilter.java
@@ -39,13 +39,14 @@ public class DelegateFileFilter extends AbstractFileFilter implements Serializab
/** The File filter */
private final transient FileFilter fileFilter;
+
/** The Filename filter */
private final transient FilenameFilter fileNameFilter;
/**
* Constructs a delegate file filter around an existing FileFilter.
*
- * @param fileFilter the filter to decorate
+ * @param fileFilter The filter to decorate.
*/
public DelegateFileFilter(final FileFilter fileFilter) {
Objects.requireNonNull(fileFilter, "filter");
@@ -56,7 +57,7 @@ public DelegateFileFilter(final FileFilter fileFilter) {
/**
* Constructs a delegate file filter around an existing FilenameFilter.
*
- * @param fileNameFilter the filter to decorate
+ * @param fileNameFilter The filter to decorate.
*/
public DelegateFileFilter(final FilenameFilter fileNameFilter) {
Objects.requireNonNull(fileNameFilter, "filter");
@@ -67,8 +68,8 @@ public DelegateFileFilter(final FilenameFilter fileNameFilter) {
/**
* Tests the filter.
*
- * @param file the file to check
- * @return true if the filter matches
+ * @param file The file to check.
+ * @return true if the filter matches.
*/
@Override
public boolean accept(final File file) {
@@ -81,9 +82,9 @@ public boolean accept(final File file) {
/**
* Tests the filter.
*
- * @param dir the directory
- * @param name the file name in the directory
- * @return true if the filter matches
+ * @param dir The directory.
+ * @param name The file name in the directory.
+ * @return true if the filter matches.
*/
@Override
public boolean accept(final File dir, final String name) {
@@ -96,7 +97,7 @@ public boolean accept(final File dir, final String name) {
/**
* Provide a String representation of this file filter.
*
- * @return a String representation
+ * @return A String representation.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/DirectoryFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/DirectoryFileFilter.java
index bb3d615bd43..446d990289b 100644
--- a/src/main/java/org/apache/commons/io/filefilter/DirectoryFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/DirectoryFileFilter.java
@@ -92,8 +92,8 @@ protected DirectoryFileFilter() {
/**
* Tests to see if the file is a directory.
*
- * @param file the File to check
- * @return true if the file is a directory
+ * @param file The File to check.
+ * @return true if the file is a directory.
*/
@Override
public boolean accept(final File file) {
@@ -103,9 +103,9 @@ public boolean accept(final File file) {
/**
* Tests to see if the file is a directory.
*
- * @param file the File to check
- * @param attributes the path's basic attributes (may be null).
- * @return true if the file is a directory
+ * @param file The File to check.
+ * @param attributes The path's basic attributes (may be null).
+ * @return true if the file is a directory.
* @since 2.9.0
*/
@Override
diff --git a/src/main/java/org/apache/commons/io/filefilter/EmptyFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/EmptyFileFilter.java
index a5cdd676bb1..b767d7a1cbf 100644
--- a/src/main/java/org/apache/commons/io/filefilter/EmptyFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/EmptyFileFilter.java
@@ -99,7 +99,7 @@ protected EmptyFileFilter() {
/**
* Tests to see if the file is empty.
*
- * @param file the file or directory to check
+ * @param file The file or directory to check.
* @return {@code true} if the file or directory is empty, otherwise {@code false}.
*/
@Override
@@ -117,8 +117,8 @@ public boolean accept(final File file) {
/**
* Tests to see if the file is empty.
*
- * @param file the file or directory to check
- * @param attributes the path's basic attributes (may be null).
+ * @param file The file or directory to check.
+ * @param attributes The path's basic attributes (may be null).
* @return {@code true} if the file or directory is empty, otherwise {@code false}.
* @since 2.9.0
*/
diff --git a/src/main/java/org/apache/commons/io/filefilter/FalseFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/FalseFileFilter.java
index ebaa77b2007..a4100ef59ca 100644
--- a/src/main/java/org/apache/commons/io/filefilter/FalseFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/FalseFileFilter.java
@@ -60,8 +60,8 @@ protected FalseFileFilter() {
/**
* Returns false.
*
- * @param file the file to check (ignored)
- * @return false
+ * @param file The file to check (ignored).
+ * @return false.
*/
@Override
public boolean accept(final File file) {
@@ -71,9 +71,9 @@ public boolean accept(final File file) {
/**
* Returns false.
*
- * @param dir the directory to check (ignored)
- * @param name the file name (ignored)
- * @return false
+ * @param dir The directory to check (ignored).
+ * @param name The file name (ignored).
+ * @return false.
*/
@Override
public boolean accept(final File dir, final String name) {
@@ -83,9 +83,9 @@ public boolean accept(final File dir, final String name) {
/**
* Returns false.
*
- * @param file the file to check (ignored)
- * @param attributes the path's basic attributes (may be null).
- * @return false
+ * @param file The file to check (ignored).
+ * @param attributes The path's basic attributes (may be null).
+ * @return {@link FileVisitResult#TERMINATE}.
* @since 2.9.0
*/
@Override
diff --git a/src/main/java/org/apache/commons/io/filefilter/FileFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/FileFileFilter.java
index 801d39f07b4..1d017859e5a 100644
--- a/src/main/java/org/apache/commons/io/filefilter/FileFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/FileFileFilter.java
@@ -92,8 +92,8 @@ protected FileFileFilter() {
/**
* Tests to see if the file is a file.
*
- * @param file the File to check
- * @return true if the file is a file
+ * @param file The File to check.
+ * @return true if the file is a file.
*/
@Override
public boolean accept(final File file) {
@@ -103,9 +103,9 @@ public boolean accept(final File file) {
/**
* Tests to see if the file is a file.
*
- * @param file the File to check
- * @param attributes the path's basic attributes (may be null).
- * @return true if the file is a file
+ * @param file The File to check.
+ * @param attributes The path's basic attributes (may be null).
+ * @return true if the file is a file.
* @since 2.9.0
*/
@Override
diff --git a/src/main/java/org/apache/commons/io/filefilter/FileFilterUtils.java b/src/main/java/org/apache/commons/io/filefilter/FileFilterUtils.java
index 5e37676ac9c..ff80abdaf1b 100644
--- a/src/main/java/org/apache/commons/io/filefilter/FileFilterUtils.java
+++ b/src/main/java/org/apache/commons/io/filefilter/FileFilterUtils.java
@@ -55,8 +55,8 @@ public class FileFilterUtils {
* Returns a filter that returns true if the file was last modified before
* or at the specified cutoff date.
*
- * @param cutoffDate the time threshold
- * @return an appropriately configured age file filter
+ * @param cutoffDate The time threshold.
+ * @return An appropriately configured age file filter.
* @see AgeFileFilter
* @since 1.2
*/
@@ -67,9 +67,9 @@ public static IOFileFilter ageFileFilter(final Date cutoffDate) {
/**
* Returns a filter that filters files based on a cutoff date.
*
- * @param cutoffDate the time threshold
- * @param acceptOlder if true, older files get accepted, if false, newer
- * @return an appropriately configured age file filter
+ * @param cutoffDate The time threshold.
+ * @param acceptOlder if true, older files get accepted, if false, newer.
+ * @return An appropriately configured age file filter.
* @see AgeFileFilter
* @since 1.2
*/
@@ -81,9 +81,9 @@ public static IOFileFilter ageFileFilter(final Date cutoffDate, final boolean ac
* Returns a filter that returns true if the file was last modified before
* or at the same time as the specified reference file.
*
- * @param cutoffReference the file whose last modification
- * time is used as the threshold age of the files
- * @return an appropriately configured age file filter
+ * @param cutoffReference The file whose last modification
+ * time is used as the threshold age of the files.
+ * @return An appropriately configured age file filter.
* @see AgeFileFilter
* @since 1.2
*/
@@ -94,10 +94,10 @@ public static IOFileFilter ageFileFilter(final File cutoffReference) {
/**
* Returns a filter that filters files based on a cutoff reference file.
*
- * @param cutoffReference the file whose last modification
- * time is used as the threshold age of the files
- * @param acceptOlder if true, older files get accepted, if false, newer
- * @return an appropriately configured age file filter
+ * @param cutoffReference The file whose last modification
+ * time is used as the threshold age of the files.
+ * @param acceptOlder if true, older files get accepted, if false, newer.
+ * @return An appropriately configured age file filter.
* @see AgeFileFilter
* @since 1.2
*/
@@ -109,8 +109,8 @@ public static IOFileFilter ageFileFilter(final File cutoffReference, final boole
* Returns a filter that returns true if the file was last modified before
* or at the specified cutoff time.
*
- * @param cutoffMillis the time threshold
- * @return an appropriately configured age file filter
+ * @param cutoffMillis The time threshold.
+ * @return An appropriately configured age file filter.
* @see AgeFileFilter
* @since 1.2
*/
@@ -121,9 +121,9 @@ public static IOFileFilter ageFileFilter(final long cutoffMillis) {
/**
* Returns a filter that filters files based on a cutoff time.
*
- * @param cutoffMillis the time threshold
- * @param acceptOlder if true, older files get accepted, if false, newer
- * @return an appropriately configured age file filter
+ * @param cutoffMillis The time threshold.
+ * @param acceptOlder if true, older files get accepted, if false, newer.
+ * @return An appropriately configured age file filter.
* @see AgeFileFilter
* @since 1.2
*/
@@ -134,8 +134,8 @@ public static IOFileFilter ageFileFilter(final long cutoffMillis, final boolean
/**
* Returns a filter that ANDs the specified filters.
*
- * @param filters the IOFileFilters that will be ANDed together.
- * @return a filter that ANDs the specified filters
+ * @param filters The IOFileFilters that will be ANDed together.
+ * @return A filter that ANDs the specified filters.
* @throws IllegalArgumentException if the filters are null or contain a
* null value.
* @see AndFileFilter
@@ -148,12 +148,12 @@ public static IOFileFilter and(final IOFileFilter... filters) {
/**
* Returns a filter that ANDs the two specified filters.
*
- * @param filter1 the first filter
- * @param filter2 the second filter
- * @return a filter that ANDs the two specified filters
+ * @param filter1 The first filter.
+ * @param filter2 The second filter.
+ * @return A filter that ANDs the two specified filters.
* @see #and(IOFileFilter...)
* @see AndFileFilter
- * @deprecated use {@link #and(IOFileFilter...)}
+ * @deprecated Use {@link #and(IOFileFilter...)}
*/
@Deprecated
public static IOFileFilter andFileFilter(final IOFileFilter filter1, final IOFileFilter filter2) {
@@ -164,8 +164,8 @@ public static IOFileFilter andFileFilter(final IOFileFilter filter1, final IOFil
* Returns an {@link IOFileFilter} that wraps the
* {@link FileFilter} instance.
*
- * @param filter the filter to be wrapped
- * @return a new filter that implements IOFileFilter
+ * @param filter The filter to be wrapped.
+ * @return A new filter that implements IOFileFilter.
* @see DelegateFileFilter
*/
public static IOFileFilter asFileFilter(final FileFilter filter) {
@@ -176,8 +176,8 @@ public static IOFileFilter asFileFilter(final FileFilter filter) {
* Returns an {@link IOFileFilter} that wraps the
* {@link FilenameFilter} instance.
*
- * @param filter the filter to be wrapped
- * @return a new filter that implements IOFileFilter
+ * @param filter The filter to be wrapped.
+ * @return A new filter that implements IOFileFilter.
* @see DelegateFileFilter
*/
public static IOFileFilter asFileFilter(final FilenameFilter filter) {
@@ -187,7 +187,7 @@ public static IOFileFilter asFileFilter(final FilenameFilter filter) {
/**
* Returns a filter that checks if the file is a directory.
*
- * @return file filter that accepts only directories and not files
+ * @return file filter that accepts only directories and not files.
* @see DirectoryFileFilter#DIRECTORY
*/
public static IOFileFilter directoryFileFilter() {
@@ -197,7 +197,7 @@ public static IOFileFilter directoryFileFilter() {
/**
* Returns a filter that always returns false.
*
- * @return a false filter
+ * @return A false filter.
* @see FalseFileFilter#FALSE
*/
public static IOFileFilter falseFileFilter() {
@@ -207,7 +207,7 @@ public static IOFileFilter falseFileFilter() {
/**
* Returns a filter that checks if the file is a file (and not a directory).
*
- * @return file filter that accepts only files and not directories
+ * @return file filter that accepts only files and not directories.
* @see FileFileFilter#INSTANCE
*/
public static IOFileFilter fileFileFilter() {
@@ -226,13 +226,13 @@ public static IOFileFilter fileFileFilter() {
* Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
* FileFilterUtils.suffixFileFilter(".java"));
*
- * @param filter the filter to apply to the set of files.
- * @param files the array of files to apply the filter to.
- * @return a subset of {@code files} that is accepted by the
+ *
+ * @param filter The filter to apply to the set of files.
+ * @param files The array of files to apply the filter to.
+ * @return A subset of {@code files} that is accepted by the
* file filter.
* @throws NullPointerException if the filter is {@code null}
* or {@code files} contains a {@code null} value.
- *
* @since 2.0
*/
public static File[] filter(final IOFileFilter filter, final File... files) {
@@ -259,13 +259,13 @@ public static File[] filter(final IOFileFilter filter, final File... files) {
* Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
* FileFilterUtils.suffixFileFilter(".java"));
*
- * @param filter the filter to apply to each files in the list.
- * @param files the collection of files to apply the filter to.
- * @return a subset of {@code files} that is accepted by the
+ *
+ * @param filter The filter to apply to each files in the list.
+ * @param files The collection of files to apply the filter to.
+ * @return A subset of {@code files} that is accepted by the
* file filter.
* @throws IllegalArgumentException if the filter is {@code null}
* @since 2.0
@@ -369,9 +371,10 @@ public static List filterList(final IOFileFilter filter, final Iterable
- * @param filter the filter to apply to the set of files.
- * @param files the collection of files to apply the filter to.
- * @return a subset of {@code files} that is accepted by the
+ *
+ * @param filter The filter to apply to the set of files.
+ * @param files The collection of files to apply the filter to.
+ * @return A subset of {@code files} that is accepted by the
* file filter.
* @throws IllegalArgumentException if the filter is {@code null}
* or {@code files} contains a {@code null} value.
@@ -398,9 +401,10 @@ public static Set filterSet(final IOFileFilter filter, final File... files
* Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
* FileFilterUtils.suffixFileFilter(".java"));
*
- * @param filter the filter to apply to the set of files.
- * @param files the collection of files to apply the filter to.
- * @return a subset of {@code files} that is accepted by the
+ *
+ * @param filter The filter to apply to the set of files.
+ * @param files The collection of files to apply the filter to.
+ * @return A subset of {@code files} that is accepted by the
* file filter.
* @throws IllegalArgumentException if the filter is {@code null}
* @since 2.0
@@ -416,10 +420,10 @@ public static Set filterSet(final IOFileFilter filter, final Iterable toList(final IOFileFilter... filters) {
/**
* Returns a filter that always returns true.
*
- * @return a true filter
+ * @return A true filter.
* @see TrueFileFilter#TRUE
*/
public static IOFileFilter trueFileFilter() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/HiddenFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/HiddenFileFilter.java
index 6fff2241ab1..d76fd9e2516 100644
--- a/src/main/java/org/apache/commons/io/filefilter/HiddenFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/HiddenFileFilter.java
@@ -95,7 +95,7 @@ protected HiddenFileFilter() {
/**
* Tests to see if the file is hidden.
*
- * @param file the File to check
+ * @param file The File to check.
* @return {@code true} if the file is
* hidden, otherwise {@code false}.
*/
@@ -107,8 +107,8 @@ public boolean accept(final File file) {
/**
* Tests to see if the file is hidden.
*
- * @param file the File to check
- * @param attributes the path's basic attributes (may be null).
+ * @param file The File to check.
+ * @param attributes The path's basic attributes (may be null).
* @return {@code true} if the file is hidden, otherwise {@code false}.
* @since 2.9.0
*/
diff --git a/src/main/java/org/apache/commons/io/filefilter/IOFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/IOFileFilter.java
index 17bf6478af4..e8185c95dce 100644
--- a/src/main/java/org/apache/commons/io/filefilter/IOFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/IOFileFilter.java
@@ -44,7 +44,7 @@ public interface IOFileFilter extends FileFilter, FilenameFilter, PathFilter, Pa
* Defined in {@link FileFilter}.
*
*
- * @param file the File to check.
+ * @param file The File to check.
* @return true if this file matches the test.
*/
@Override
@@ -56,8 +56,8 @@ public interface IOFileFilter extends FileFilter, FilenameFilter, PathFilter, Pa
* Defined in {@link FilenameFilter}.
*
*
- * @param dir the directory File to check.
- * @param name the file name within the directory to check.
+ * @param dir The directory File to check.
+ * @param name The file name within the directory to check.
* @return true if this file matches the test.
*/
@Override
@@ -66,8 +66,8 @@ public interface IOFileFilter extends FileFilter, FilenameFilter, PathFilter, Pa
/**
* Checks to see if a Path should be accepted by this filter.
*
- * @param path the Path to check.
- * @param attributes the path's basic attributes (may be null).
+ * @param path The Path to check.
+ * @param attributes The path's basic attributes (may be null).
* @return true if this path matches the test.
* @since 2.9.0
*/
@@ -79,8 +79,8 @@ default FileVisitResult accept(final Path path, final BasicFileAttributes attrib
/**
* Constructs a new "and" filter with this filter.
*
- * @param fileFilter the filter to "and".
- * @return a new filter.
+ * @param fileFilter The filter to "and".
+ * @return A new filter.
* @since 2.9.0
*/
default IOFileFilter and(final IOFileFilter fileFilter) {
@@ -90,7 +90,7 @@ default IOFileFilter and(final IOFileFilter fileFilter) {
/**
* Tests if a Path should be accepted by this filter.
*
- * @param path the Path to check.
+ * @param path The Path to check.
* @return true if this path matches the test.
* @since 2.14.0
*/
@@ -102,7 +102,7 @@ default boolean matches(final Path path) {
/**
* Constructs a new "not" filter with this filter.
*
- * @return a new filter.
+ * @return A new filter.
* @since 2.9.0
*/
default IOFileFilter negate() {
@@ -112,8 +112,8 @@ default IOFileFilter negate() {
/**
* Constructs a new "or" filter with this filter.
*
- * @param fileFilter the filter to "or".
- * @return a new filter.
+ * @param fileFilter The filter to "or".
+ * @return A new filter.
* @since 2.9.0
*/
default IOFileFilter or(final IOFileFilter fileFilter) {
diff --git a/src/main/java/org/apache/commons/io/filefilter/MagicNumberFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/MagicNumberFileFilter.java
index 79aa55d68c1..20e994114a6 100644
--- a/src/main/java/org/apache/commons/io/filefilter/MagicNumberFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/MagicNumberFileFilter.java
@@ -138,7 +138,7 @@ public class MagicNumberFileFilter extends AbstractFileFilter implements Seriali
* (byte) 0xBA, (byte) 0xBE});
*
*
- * @param magicNumber the magic number to look for in the file.
+ * @param magicNumber The magic number to look for in the file.
* @throws IllegalArgumentException if {@code magicNumber} is
* {@code null}, or contains no bytes.
*/
@@ -163,8 +163,8 @@ public MagicNumberFileFilter(final byte[] magicNumber) {
* MagicNumberFileFilter(new byte[] {0xCA, 0xFE, 0xBA, 0xBE}, 0);
*
*
- * @param magicNumbers the magic number to look for in the file.
- * @param offset the byte offset in the file to start comparing bytes.
+ * @param magicNumbers The magic number to look for in the file.
+ * @param offset The byte offset in the file to start comparing bytes.
* @throws IllegalArgumentException if {@code magicNumber}
* contains no bytes, or {@code offset}
* is a negative number.
@@ -197,7 +197,7 @@ public MagicNumberFileFilter(final byte[] magicNumbers, final long offset) {
* }
*
*
- * @param magicNumber the magic number to look for in the file.
+ * @param magicNumber The magic number to look for in the file.
* The string is converted to bytes using the platform default charset.
*
* @throws IllegalArgumentException if {@code magicNumber} is
@@ -218,12 +218,12 @@ public MagicNumberFileFilter(final String magicNumber) {
* MagicNumberFileFilter tarFileFilter = MagicNumberFileFilter("ustar", 257);
*
*
- * This method uses the virtual machine's {@link Charset#defaultCharset() default charset}.
+ * This method uses the virtual machine's {@linkplain Charset#defaultCharset() default charset}.
*
*
- * @param magicNumber the magic number to look for in the file.
+ * @param magicNumber The magic number to look for in the file.
* The string is converted to bytes using the platform default charset.
- * @param offset the byte offset in the file to start comparing bytes.
+ * @param offset The byte offset in the file to start comparing bytes.
* @throws IllegalArgumentException if {@code magicNumber} is
* the empty String, or {@code offset} is
* a negative number.
@@ -243,7 +243,7 @@ public MagicNumberFileFilter(final String magicNumber, final long offset) {
* be rejected.
*
*
- * @param file the file to accept or reject.
+ * @param file The file to accept or reject.
* @return {@code true} if the file contains the filter's magic number
* at the specified offset, {@code false} otherwise.
*/
@@ -270,8 +270,9 @@ public boolean accept(final File file) {
* be rejected.
*
*
- * @param file the file to accept or reject.
- * @param attributes the path's basic attributes (may be null).
+ *
+ * @param file The file to accept or reject.
+ * @param attributes The path's basic attributes (may be null).
* @return {@code true} if the file contains the filter's magic number
* at the specified offset, {@code false} otherwise.
* @since 2.9.0
@@ -300,7 +301,7 @@ public FileVisitResult accept(final Path file, final BasicFileAttributes attribu
* Returns a String representation of the file filter, which includes the
* magic number bytes and byte offset.
*
- * @return a String representation of the file filter.
+ * @return A String representation of the file filter.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/NameFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/NameFileFilter.java
index 7eda934d906..c631ecc6829 100644
--- a/src/main/java/org/apache/commons/io/filefilter/NameFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/NameFileFilter.java
@@ -83,9 +83,9 @@ public class NameFileFilter extends AbstractFileFilter implements Serializable {
/**
* Constructs a new case-sensitive name file filter for a list of names.
*
- * @param names the names to allow, must not be null
- * @throws IllegalArgumentException if the name list is null
- * @throws ClassCastException if the list does not contain Strings
+ * @param names The names to allow, must not be null.
+ * @throws IllegalArgumentException if the name list is null.
+ * @throws ClassCastException if the list does not contain Strings.
*/
public NameFileFilter(final List names) {
this(names, null);
@@ -94,10 +94,10 @@ public NameFileFilter(final List names) {
/**
* Constructs a new name file filter for a list of names specifying case-sensitivity.
*
- * @param names the names to allow, must not be null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws NullPointerException if the name list is null
- * @throws ClassCastException if the list does not contain Strings
+ * @param names The names to allow, must not be null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws NullPointerException if the name list is null.
+ * @throws ClassCastException if the list does not contain Strings.
*/
public NameFileFilter(final List names, final IOCase ioCase) {
Objects.requireNonNull(names, "names");
@@ -108,8 +108,8 @@ public NameFileFilter(final List names, final IOCase ioCase) {
/**
* Constructs a new case-sensitive name file filter for a single name.
*
- * @param name the name to allow, must not be null
- * @throws IllegalArgumentException if the name is null
+ * @param name The name to allow, must not be null.
+ * @throws IllegalArgumentException if the name is null.
*/
public NameFileFilter(final String name) {
this(name, IOCase.SENSITIVE);
@@ -122,8 +122,8 @@ public NameFileFilter(final String name) {
* instance. This would be inadvisable however.
*
*
- * @param names the names to allow, must not be null
- * @throws IllegalArgumentException if the names array is null
+ * @param names The names to allow, must not be null.
+ * @throws IllegalArgumentException if the names array is null.
*/
public NameFileFilter(final String... names) {
this(names, IOCase.SENSITIVE);
@@ -132,9 +132,9 @@ public NameFileFilter(final String... names) {
/**
* Constructs a new name file filter specifying case-sensitivity.
*
- * @param name the name to allow, must not be null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws NullPointerException if the name is null
+ * @param name The name to allow, must not be null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws NullPointerException if the name is null.
*/
public NameFileFilter(final String name, final IOCase ioCase) {
Objects.requireNonNull(name, "name");
@@ -145,9 +145,9 @@ public NameFileFilter(final String name, final IOCase ioCase) {
/**
* Constructs a new name file filter for an array of names specifying case-sensitivity.
*
- * @param names the names to allow, must not be null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws NullPointerException if the names array is null
+ * @param names The names to allow, must not be null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws NullPointerException if the names array is null.
*/
public NameFileFilter(final String[] names, final IOCase ioCase) {
Objects.requireNonNull(names, "names");
@@ -158,8 +158,8 @@ public NameFileFilter(final String[] names, final IOCase ioCase) {
/**
* Tests to see if the file name matches.
*
- * @param file the File to check
- * @return true if the file name matches
+ * @param file The File to check.
+ * @return true if the file name matches.
*/
@Override
public boolean accept(final File file) {
@@ -169,9 +169,9 @@ public boolean accept(final File file) {
/**
* Tests to see if the file name matches.
*
- * @param dir the File directory (ignored)
- * @param name the file name
- * @return true if the file name matches
+ * @param dir The File directory (ignored).
+ * @param name The file name.
+ * @return true if the file name matches.
*/
@Override
public boolean accept(final File dir, final String name) {
@@ -181,9 +181,9 @@ public boolean accept(final File dir, final String name) {
/**
* Checks to see if the file name matches.
*
- * @param path the File to check
- * @param attributes the path's basic attributes (may be null).
- * @return true if the file name matches
+ * @param path The File to check.
+ * @param attributes The path's basic attributes (may be null).
+ * @return true if the file name matches.
* @since 2.9.0
*/
@Override
@@ -202,7 +202,7 @@ private IOCase toIOCase(final IOCase ioCase) {
/**
* Provide a String representation of this file filter.
*
- * @return a String representation
+ * @return A String representation.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/NotFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/NotFileFilter.java
index 8592e402129..d6b776bd0af 100644
--- a/src/main/java/org/apache/commons/io/filefilter/NotFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/NotFileFilter.java
@@ -43,8 +43,8 @@ public class NotFileFilter extends AbstractFileFilter implements Serializable {
/**
* Constructs a new file filter that NOTs the result of another filter.
*
- * @param filter the filter, must not be null
- * @throws NullPointerException if the filter is null
+ * @param filter The filter, must not be null.
+ * @throws NullPointerException if the filter is null.
*/
public NotFileFilter(final IOFileFilter filter) {
Objects.requireNonNull(filter, "filter");
@@ -54,8 +54,8 @@ public NotFileFilter(final IOFileFilter filter) {
/**
* Returns the logical NOT of the underlying filter's return value for the same File.
*
- * @param file the File to check
- * @return true if the filter returns false
+ * @param file The File to check.
+ * @return true if the filter returns false.
*/
@Override
public boolean accept(final File file) {
@@ -65,9 +65,9 @@ public boolean accept(final File file) {
/**
* Returns the logical NOT of the underlying filter's return value for the same arguments.
*
- * @param file the File directory
- * @param name the file name
- * @return true if the filter returns false
+ * @param file The File directory.
+ * @param name The file name.
+ * @return true if the filter returns false.
*/
@Override
public boolean accept(final File file, final String name) {
@@ -77,9 +77,9 @@ public boolean accept(final File file, final String name) {
/**
* Returns the logical NOT of the underlying filter's return value for the same File.
*
- * @param file the File to check
- * @param attributes the path's basic attributes (may be null).
- * @return true if the filter returns false
+ * @param file The File to check.
+ * @param attributes The path's basic attributes (may be null).
+ * @return true if the filter returns false.
* @since 2.9.0
*/
@Override
@@ -94,7 +94,7 @@ private FileVisitResult not(final FileVisitResult accept) {
/**
* Provide a String representation of this file filter.
*
- * @return a String representation
+ * @return A String representation.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/OrFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/OrFileFilter.java
index 57b8bcf0560..aeb0a4ec3fb 100644
--- a/src/main/java/org/apache/commons/io/filefilter/OrFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/OrFileFilter.java
@@ -59,7 +59,7 @@ public OrFileFilter() {
/**
* Constructs a new instance with the given initial list.
*
- * @param initialList the initial list.
+ * @param initialList The initial list.
*/
private OrFileFilter(final ArrayList initialList) {
this.fileFilters = Objects.requireNonNull(initialList, "initialList");
@@ -68,7 +68,7 @@ private OrFileFilter(final ArrayList initialList) {
/**
* Constructs a new instance with the given initial capacity.
*
- * @param initialCapacity the initial capacity.
+ * @param initialCapacity The initial capacity.
*/
private OrFileFilter(final int initialCapacity) {
this(new ArrayList<>(initialCapacity));
@@ -76,6 +76,7 @@ private OrFileFilter(final int initialCapacity) {
/**
* Constructs a new instance for the give filters.
+ *
* @param fileFilters filters to OR.
* @since 2.9.0
*/
@@ -87,9 +88,9 @@ public OrFileFilter(final IOFileFilter... fileFilters) {
/**
* Constructs a new file filter that ORs the result of other filters.
*
- * @param filter1 the first filter, must not be null
- * @param filter2 the second filter, must not be null
- * @throws IllegalArgumentException if either filter is null
+ * @param filter1 The first filter, must not be null.
+ * @param filter2 The second filter, must not be null.
+ * @throws IllegalArgumentException if either filter is null.
*/
public OrFileFilter(final IOFileFilter filter1, final IOFileFilter filter2) {
this(2);
@@ -100,7 +101,7 @@ public OrFileFilter(final IOFileFilter filter1, final IOFileFilter filter2) {
/**
* Constructs a new instance of {@link OrFileFilter} with the specified filters.
*
- * @param fileFilters the file filters for this filter, copied.
+ * @param fileFilters The file filters for this filter, copied.
* @since 1.1
*/
public OrFileFilter(final List fileFilters) {
@@ -142,7 +143,7 @@ public void addFileFilter(final IOFileFilter fileFilter) {
/**
* Adds the given file filters.
*
- * @param fileFilters the filters to add.
+ * @param fileFilters The filters to add.
* @since 2.9.0
*/
public void addFileFilter(final IOFileFilter... fileFilters) {
@@ -177,7 +178,7 @@ public void setFileFilters(final List fileFilters) {
/**
* Provide a String representation of this file filter.
*
- * @return a String representation
+ * @return A String representation.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/PrefixFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/PrefixFileFilter.java
index 3a85c9e8e18..edf1224f6e0 100644
--- a/src/main/java/org/apache/commons/io/filefilter/PrefixFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/PrefixFileFilter.java
@@ -83,9 +83,9 @@ public class PrefixFileFilter extends AbstractFileFilter implements Serializable
/**
* Constructs a new Prefix file filter for a list of prefixes.
*
- * @param prefixes the prefixes to allow, must not be null
- * @throws NullPointerException if the prefix list is null
- * @throws ClassCastException if the list does not contain Strings
+ * @param prefixes The prefixes to allow, must not be null.
+ * @throws NullPointerException if the prefix list is null.
+ * @throws ClassCastException if the list does not contain Strings.
*/
public PrefixFileFilter(final List prefixes) {
this(prefixes, IOCase.SENSITIVE);
@@ -95,10 +95,10 @@ public PrefixFileFilter(final List prefixes) {
* Constructs a new Prefix file filter for a list of prefixes
* specifying case-sensitivity.
*
- * @param prefixes the prefixes to allow, must not be null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws NullPointerException if the prefix list is null
- * @throws ClassCastException if the list does not contain Strings
+ * @param prefixes The prefixes to allow, must not be null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws NullPointerException if the prefix list is null.
+ * @throws ClassCastException if the list does not contain Strings.
* @since 1.4
*/
public PrefixFileFilter(final List prefixes, final IOCase ioCase) {
@@ -110,8 +110,8 @@ public PrefixFileFilter(final List prefixes, final IOCase ioCase) {
/**
* Constructs a new Prefix file filter for a single prefix.
*
- * @param prefix the prefix to allow, must not be null
- * @throws IllegalArgumentException if the prefix is null
+ * @param prefix The prefix to allow, must not be null.
+ * @throws IllegalArgumentException if the prefix is null.
*/
public PrefixFileFilter(final String prefix) {
this(prefix, IOCase.SENSITIVE);
@@ -124,8 +124,8 @@ public PrefixFileFilter(final String prefix) {
* instance. This would be inadvisable however.
*
*
- * @param prefixes the prefixes to allow, must not be null
- * @throws IllegalArgumentException if the prefix array is null
+ * @param prefixes The prefixes to allow, must not be null.
+ * @throws IllegalArgumentException if the prefix array is null.
*/
public PrefixFileFilter(final String... prefixes) {
this(prefixes, IOCase.SENSITIVE);
@@ -135,9 +135,9 @@ public PrefixFileFilter(final String... prefixes) {
* Constructs a new Prefix file filter for a single prefix
* specifying case-sensitivity.
*
- * @param prefix the prefix to allow, must not be null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the prefix is null
+ * @param prefix The prefix to allow, must not be null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws IllegalArgumentException if the prefix is null.
* @since 1.4
*/
public PrefixFileFilter(final String prefix, final IOCase ioCase) {
@@ -150,9 +150,9 @@ public PrefixFileFilter(final String prefix, final IOCase ioCase) {
* Constructs a new Prefix file filter for any of an array of prefixes
* specifying case-sensitivity.
*
- * @param prefixes the prefixes to allow, must not be null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the prefix is null
+ * @param prefixes The prefixes to allow, must not be null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws IllegalArgumentException if the prefix is null.
* @since 1.4
*/
public PrefixFileFilter(final String[] prefixes, final IOCase ioCase) {
@@ -164,8 +164,8 @@ public PrefixFileFilter(final String[] prefixes, final IOCase ioCase) {
/**
* Tests to see if the file name starts with the prefix.
*
- * @param file the File to check
- * @return true if the file name starts with one of our prefixes
+ * @param file The File to check.
+ * @return true if the file name starts with one of our prefixes.
*/
@Override
public boolean accept(final File file) {
@@ -175,9 +175,9 @@ public boolean accept(final File file) {
/**
* Tests to see if the file name starts with the prefix.
*
- * @param file the File directory
- * @param name the file name
- * @return true if the file name starts with one of our prefixes
+ * @param file The File directory.
+ * @param name The file name.
+ * @return true if the file name starts with one of our prefixes.
*/
@Override
public boolean accept(final File file, final String name) {
@@ -187,9 +187,9 @@ public boolean accept(final File file, final String name) {
/**
* Tests to see if the file name starts with the prefix.
*
- * @param file the File to check
- * @param attributes the path's basic attributes (may be null).
- * @return true if the file name starts with one of our prefixes
+ * @param file The File to check.
+ * @param attributes The path's basic attributes (may be null).
+ * @return true if the file name starts with one of our prefixes.
* @since 2.9.0
*/
@Override
@@ -204,7 +204,7 @@ private boolean accept(final String name) {
/**
* Provides a String representation of this file filter.
*
- * @return a String representation
+ * @return A String representation.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/RegexFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/RegexFileFilter.java
index f044800692c..2ab5b6d10d1 100644
--- a/src/main/java/org/apache/commons/io/filefilter/RegexFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/RegexFileFilter.java
@@ -79,9 +79,9 @@ public class RegexFileFilter extends AbstractFileFilter implements Serializable
/**
* Compiles the given pattern source.
*
- * @param pattern the source pattern.
- * @param flags the compilation flags.
- * @return a new Pattern.
+ * @param pattern The source pattern.
+ * @param flags The compilation flags.
+ * @return A new Pattern.
*/
private static Pattern compile(final String pattern, final int flags) {
Objects.requireNonNull(pattern, "pattern");
@@ -132,8 +132,8 @@ public RegexFileFilter(final Pattern pattern, final Function pathT
/**
* Constructs a new regular expression filter.
*
- * @param pattern regular string expression to match
- * @throws NullPointerException if the pattern is null
+ * @param pattern regular string expression to match.
+ * @throws NullPointerException if the pattern is null.
*/
public RegexFileFilter(final String pattern) {
this(pattern, 0);
@@ -142,9 +142,9 @@ public RegexFileFilter(final String pattern) {
/**
* Constructs a new regular expression filter with the specified flags.
*
- * @param pattern regular string expression to match
+ * @param pattern regular string expression to match.
* @param flags pattern flags - e.g. {@link Pattern#CASE_INSENSITIVE}
- * @throws IllegalArgumentException if the pattern is null
+ * @throws IllegalArgumentException if the pattern is null.
*/
public RegexFileFilter(final String pattern, final int flags) {
this(compile(pattern, flags));
@@ -153,9 +153,9 @@ public RegexFileFilter(final String pattern, final int flags) {
/**
* Constructs a new regular expression filter with the specified flags case sensitivity.
*
- * @param pattern regular string expression to match
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the pattern is null
+ * @param pattern regular string expression to match.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws IllegalArgumentException if the pattern is null.
*/
public RegexFileFilter(final String pattern, final IOCase ioCase) {
this(compile(pattern, toFlags(ioCase)));
@@ -164,9 +164,9 @@ public RegexFileFilter(final String pattern, final IOCase ioCase) {
/**
* Tests to see if the file name matches one of the regular expressions.
*
- * @param dir the file directory (ignored)
- * @param name the file name
- * @return true if the file name matches one of the regular expressions
+ * @param dir The file directory (ignored).
+ * @param name The file name.
+ * @return true if the file name matches one of the regular expressions.
*/
@Override
public boolean accept(final File dir, final String name) {
@@ -176,9 +176,9 @@ public boolean accept(final File dir, final String name) {
/**
* Tests to see if the file name matches one of the regular expressions.
*
- * @param path the path
- * @param attributes the path's basic attributes (may be null).
- * @return true if the file name matches one of the regular expressions
+ * @param path The path.
+ * @param attributes The path's basic attributes (may be null).
+ * @return true if the file name matches one of the regular expressions.
*/
@Override
public FileVisitResult accept(final Path path, final BasicFileAttributes attributes) {
diff --git a/src/main/java/org/apache/commons/io/filefilter/SizeFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/SizeFileFilter.java
index 24b0b57f939..809e9a9fce1 100644
--- a/src/main/java/org/apache/commons/io/filefilter/SizeFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/SizeFileFilter.java
@@ -82,8 +82,8 @@ public class SizeFileFilter extends AbstractFileFilter implements Serializable {
* Constructs a new size file filter for files equal to or
* larger than a certain size.
*
- * @param size the threshold size of the files
- * @throws IllegalArgumentException if the size is negative
+ * @param size The threshold size of the files.
+ * @throws IllegalArgumentException if the size is negative.
*/
public SizeFileFilter(final long size) {
this(size, true);
@@ -93,10 +93,10 @@ public SizeFileFilter(final long size) {
* Constructs a new size file filter for files based on a certain size
* threshold.
*
- * @param size the threshold size of the files
+ * @param size The threshold size of the files.
* @param acceptLarger if true, files equal to or larger are accepted,
- * otherwise smaller ones (but not equal to)
- * @throws IllegalArgumentException if the size is negative
+ * otherwise smaller ones (but not equal to).
+ * @throws IllegalArgumentException if the size is negative.
*/
public SizeFileFilter(final long size, final boolean acceptLarger) {
if (size < 0) {
@@ -115,8 +115,8 @@ public SizeFileFilter(final long size, final boolean acceptLarger) {
* file IS selected.
*
*
- * @param file the File to check
- * @return true if the file name matches
+ * @param file The File to check.
+ * @return true if the file name matches.
*/
@Override
public boolean accept(final File file) {
@@ -134,9 +134,9 @@ private boolean accept(final long length) {
* file IS selected.
*
*
- * @param file the File to check
- * @param attributes the path's basic attributes (may be null).
- * @return true if the file name matches
+ * @param file The File to check.
+ * @param attributes The path's basic attributes (may be null).
+ * @return true if the file name matches.
*/
@Override
public FileVisitResult accept(final Path file, final BasicFileAttributes attributes) {
@@ -146,7 +146,7 @@ public FileVisitResult accept(final Path file, final BasicFileAttributes attribu
/**
* Provide a String representation of this file filter.
*
- * @return a String representation
+ * @return A String representation.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/SuffixFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/SuffixFileFilter.java
index d375433495a..589fe613baf 100644
--- a/src/main/java/org/apache/commons/io/filefilter/SuffixFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/SuffixFileFilter.java
@@ -84,9 +84,9 @@ public class SuffixFileFilter extends AbstractFileFilter implements Serializable
/**
* Constructs a new Suffix file filter for a list of suffixes.
*
- * @param suffixes the suffixes to allow, must not be null
- * @throws IllegalArgumentException if the suffix list is null
- * @throws ClassCastException if the list does not contain Strings
+ * @param suffixes The suffixes to allow, must not be null.
+ * @throws IllegalArgumentException if the suffix list is null.
+ * @throws ClassCastException if the list does not contain Strings.
*/
public SuffixFileFilter(final List suffixes) {
this(suffixes, IOCase.SENSITIVE);
@@ -96,10 +96,10 @@ public SuffixFileFilter(final List suffixes) {
* Constructs a new Suffix file filter for a list of suffixes
* specifying case-sensitivity.
*
- * @param suffixes the suffixes to allow, must not be null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the suffix list is null
- * @throws ClassCastException if the list does not contain Strings
+ * @param suffixes The suffixes to allow, must not be null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws IllegalArgumentException if the suffix list is null.
+ * @throws ClassCastException if the list does not contain Strings.
* @since 1.4
*/
public SuffixFileFilter(final List suffixes, final IOCase ioCase) {
@@ -111,8 +111,8 @@ public SuffixFileFilter(final List suffixes, final IOCase ioCase) {
/**
* Constructs a new Suffix file filter for a single extension.
*
- * @param suffix the suffix to allow, must not be null
- * @throws IllegalArgumentException if the suffix is null
+ * @param suffix The suffix to allow, must not be null.
+ * @throws IllegalArgumentException if the suffix is null.
*/
public SuffixFileFilter(final String suffix) {
this(suffix, IOCase.SENSITIVE);
@@ -125,8 +125,8 @@ public SuffixFileFilter(final String suffix) {
* instance. This would be inadvisable however.
*
*
- * @param suffixes the suffixes to allow, must not be null
- * @throws NullPointerException if the suffix array is null
+ * @param suffixes The suffixes to allow, must not be null.
+ * @throws NullPointerException if the suffix array is null.
*/
public SuffixFileFilter(final String... suffixes) {
this(suffixes, IOCase.SENSITIVE);
@@ -136,9 +136,9 @@ public SuffixFileFilter(final String... suffixes) {
* Constructs a new Suffix file filter for a single extension
* specifying case-sensitivity.
*
- * @param suffix the suffix to allow, must not be null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws NullPointerException if the suffix is null
+ * @param suffix The suffix to allow, must not be null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws NullPointerException if the suffix is null.
* @since 1.4
*/
public SuffixFileFilter(final String suffix, final IOCase ioCase) {
@@ -151,9 +151,9 @@ public SuffixFileFilter(final String suffix, final IOCase ioCase) {
* Constructs a new Suffix file filter for an array of suffixes
* specifying case-sensitivity.
*
- * @param suffixes the suffixes to allow, must not be null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws NullPointerException if the suffix array is null
+ * @param suffixes The suffixes to allow, must not be null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws NullPointerException if the suffix array is null.
* @since 1.4
*/
public SuffixFileFilter(final String[] suffixes, final IOCase ioCase) {
@@ -165,8 +165,8 @@ public SuffixFileFilter(final String[] suffixes, final IOCase ioCase) {
/**
* Tests to see if the file name ends with the suffix.
*
- * @param file the File to check
- * @return true if the file name ends with one of our suffixes
+ * @param file The File to check.
+ * @return true if the file name ends with one of our suffixes.
*/
@Override
public boolean accept(final File file) {
@@ -176,9 +176,9 @@ public boolean accept(final File file) {
/**
* Tests to see if the file name ends with the suffix.
*
- * @param file the File directory
- * @param name the file name
- * @return true if the file name ends with one of our suffixes
+ * @param file The File directory.
+ * @param name The file name.
+ * @return true if the file name ends with one of our suffixes.
*/
@Override
public boolean accept(final File file, final String name) {
@@ -188,9 +188,9 @@ public boolean accept(final File file, final String name) {
/**
* Tests to see if the file name ends with the suffix.
*
- * @param path the File to check
- * @param attributes the path's basic attributes (may be null).
- * @return true if the file name ends with one of our suffixes
+ * @param path The File to check.
+ * @param attributes The path's basic attributes (may be null).
+ * @return true if the file name ends with one of our suffixes.
* @since 2.9.0
*/
@Override
@@ -205,7 +205,7 @@ private boolean accept(final String name) {
/**
* Provides a String representation of this file filter.
*
- * @return a String representation
+ * @return A String representation.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/SymbolicLinkFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/SymbolicLinkFileFilter.java
index 5c0d85a79a7..e464880b83c 100644
--- a/src/main/java/org/apache/commons/io/filefilter/SymbolicLinkFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/SymbolicLinkFileFilter.java
@@ -107,7 +107,7 @@ public SymbolicLinkFileFilter(final FileVisitResult onAccept, final FileVisitRes
/**
* Tests to see if the file is a symbolic link.
*
- * @param file the File to check
+ * @param file The File to check.
* @return true if the file exists and is a symbolic link to either another file or a directory,
* false otherwise.
*/
@@ -119,8 +119,8 @@ public boolean accept(final File file) {
/**
* Tests to see if the file is a symbolic link.
*
- * @param path the File Path to check
- * @param attributes the path's basic attributes (may be null).
+ * @param path The File Path to check.
+ * @param attributes The path's basic attributes (may be null).
* @return {@code onAccept} from {@link #SymbolicLinkFileFilter(FileVisitResult, FileVisitResult)} if the file exists and is a symbolic link to either
* another file or a directory; returns {@code onReject} otherwise.
*/
@@ -136,7 +136,7 @@ public FileVisitResult accept(final Path path, final BasicFileAttributes attribu
* test for why.)
*
*
- * @param filePath The filePath to test
+ * @param filePath The filePath to test.
* @return true if the file exists and is a symbolic link to either a file or directory, false otherwise.
*/
boolean isSymbolicLink(final Path filePath) {
diff --git a/src/main/java/org/apache/commons/io/filefilter/TrueFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/TrueFileFilter.java
index 70e27da55dc..0a1841104c6 100644
--- a/src/main/java/org/apache/commons/io/filefilter/TrueFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/TrueFileFilter.java
@@ -60,8 +60,8 @@ protected TrueFileFilter() {
/**
* Returns true.
*
- * @param file the file to check (ignored)
- * @return true
+ * @param file The file to check (ignored).
+ * @return true.
*/
@Override
public boolean accept(final File file) {
@@ -71,9 +71,9 @@ public boolean accept(final File file) {
/**
* Returns true.
*
- * @param dir the directory to check (ignored)
- * @param name the file name (ignored)
- * @return true
+ * @param dir The directory to check (ignored).
+ * @param name The file name (ignored).
+ * @return true.
*/
@Override
public boolean accept(final File dir, final String name) {
@@ -83,9 +83,9 @@ public boolean accept(final File dir, final String name) {
/**
* Returns true.
*
- * @param file the file to check (ignored)
- * @param attributes the path's basic attributes (may be null).
- * @return true
+ * @param file The file to check (ignored).
+ * @param attributes The path's basic attributes (may be null).
+ * @return true.
* @since 2.9.0
*/
@Override
diff --git a/src/main/java/org/apache/commons/io/filefilter/WildcardFileFilter.java b/src/main/java/org/apache/commons/io/filefilter/WildcardFileFilter.java
index 72a01c3789e..feb221c0901 100644
--- a/src/main/java/org/apache/commons/io/filefilter/WildcardFileFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/WildcardFileFilter.java
@@ -124,7 +124,7 @@ public Builder setIoCase(final IOCase ioCase) {
/**
* Sets the list of wildcards to match, not null.
*
- * @param wildcards the list of wildcards to match, not null.
+ * @param wildcards The list of wildcards to match, not null.
* @return {@code this} instance.
*/
public Builder setWildcards(final List wildcards) {
@@ -135,7 +135,7 @@ public Builder setWildcards(final List wildcards) {
/**
* Sets the wildcards to match, not null.
*
- * @param wildcards the wildcards to match, not null.
+ * @param wildcards The wildcards to match, not null.
* @return {@code this} instance.
*/
public Builder setWildcards(final String... wildcards) {
@@ -150,7 +150,7 @@ public Builder setWildcards(final String... wildcards) {
/**
* Constructs a new {@link Builder}.
*
- * @return a new {@link Builder}.
+ * @return A new {@link Builder}.
* @since 2.12.0
*/
public static Builder builder() {
@@ -174,9 +174,9 @@ private WildcardFileFilter(final Builder builder) {
/**
* Constructs a new wildcard filter for an array of wildcards specifying case-sensitivity.
*
- * @param wildcards the array of wildcards to match, not null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws NullPointerException if the pattern array is null
+ * @param wildcards The array of wildcards to match, not null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws NullPointerException if the pattern array is null.
*/
private WildcardFileFilter(final IOCase ioCase, final String... wildcards) {
this.wildcards = requireWildcards(wildcards).clone();
@@ -186,10 +186,10 @@ private WildcardFileFilter(final IOCase ioCase, final String... wildcards) {
/**
* Constructs a new case-sensitive wildcard filter for a list of wildcards.
*
- * @param wildcards the list of wildcards to match, not null
- * @throws IllegalArgumentException if the pattern list is null
- * @throws ClassCastException if the list does not contain Strings
- * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
+ * @param wildcards The list of wildcards to match, not null.
+ * @throws IllegalArgumentException if the pattern list is null.
+ * @throws ClassCastException if the list does not contain Strings.
+ * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}.
*/
@Deprecated
public WildcardFileFilter(final List wildcards) {
@@ -199,11 +199,11 @@ public WildcardFileFilter(final List wildcards) {
/**
* Constructs a new wildcard filter for a list of wildcards specifying case-sensitivity.
*
- * @param wildcards the list of wildcards to match, not null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the pattern list is null
- * @throws ClassCastException if the list does not contain Strings
- * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
+ * @param wildcards The list of wildcards to match, not null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws IllegalArgumentException if the pattern list is null.
+ * @throws ClassCastException if the list does not contain Strings.
+ * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}.
*/
@Deprecated
public WildcardFileFilter(final List wildcards, final IOCase ioCase) {
@@ -213,9 +213,9 @@ public WildcardFileFilter(final List wildcards, final IOCase ioCase) {
/**
* Constructs a new case-sensitive wildcard filter for a single wildcard.
*
- * @param wildcard the wildcard to match
- * @throws IllegalArgumentException if the pattern is null
- * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
+ * @param wildcard The wildcard to match.
+ * @throws IllegalArgumentException if the pattern is null.
+ * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}.
*/
@Deprecated
public WildcardFileFilter(final String wildcard) {
@@ -225,9 +225,9 @@ public WildcardFileFilter(final String wildcard) {
/**
* Constructs a new case-sensitive wildcard filter for an array of wildcards.
*
- * @param wildcards the array of wildcards to match
- * @throws NullPointerException if the pattern array is null
- * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
+ * @param wildcards The array of wildcards to match.
+ * @throws NullPointerException if the pattern array is null.
+ * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}.
*/
@Deprecated
public WildcardFileFilter(final String... wildcards) {
@@ -237,10 +237,10 @@ public WildcardFileFilter(final String... wildcards) {
/**
* Constructs a new wildcard filter for a single wildcard specifying case-sensitivity.
*
- * @param wildcard the wildcard to match, not null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws NullPointerException if the pattern is null
- * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
+ * @param wildcard The wildcard to match, not null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws NullPointerException if the pattern is null.
+ * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}.
*/
@Deprecated
public WildcardFileFilter(final String wildcard, final IOCase ioCase) {
@@ -250,10 +250,10 @@ public WildcardFileFilter(final String wildcard, final IOCase ioCase) {
/**
* Constructs a new wildcard filter for an array of wildcards specifying case-sensitivity.
*
- * @param wildcards the array of wildcards to match, not null
- * @param ioCase how to handle case sensitivity, null means case-sensitive
- * @throws NullPointerException if the pattern array is null
- * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
+ * @param wildcards The array of wildcards to match, not null.
+ * @param ioCase how to handle case sensitivity, null means case-sensitive.
+ * @throws NullPointerException if the pattern array is null.
+ * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}.
*/
@Deprecated
public WildcardFileFilter(final String[] wildcards, final IOCase ioCase) {
@@ -263,8 +263,8 @@ public WildcardFileFilter(final String[] wildcards, final IOCase ioCase) {
/**
* Tests to see if the file name matches one of the wildcards.
*
- * @param file the file to check
- * @return true if the file name matches one of the wildcards
+ * @param file The file to check.
+ * @return true if the file name matches one of the wildcards.
*/
@Override
public boolean accept(final File file) {
@@ -274,9 +274,9 @@ public boolean accept(final File file) {
/**
* Tests to see if the file name matches one of the wildcards.
*
- * @param dir the file directory (ignored)
- * @param name the file name
- * @return true if the file name matches one of the wildcards
+ * @param dir The file directory (ignored).
+ * @param name The file name.
+ * @return true if the file name matches one of the wildcards.
*/
@Override
public boolean accept(final File dir, final String name) {
@@ -286,8 +286,8 @@ public boolean accept(final File dir, final String name) {
/**
* Tests to see if the file name matches one of the wildcards.
*
- * @param path the file to check
- * @param attributes the path's basic attributes (may be null).
+ * @param path The file to check.
+ * @param attributes The path's basic attributes (may be null).
* @return true if the file name matches one of the wildcards.
* @since 2.9.0
*/
@@ -303,7 +303,7 @@ private boolean accept(final String name) {
/**
* Provide a String representation of this file filter.
*
- * @return a String representation
+ * @return A String representation.
*/
@Override
public String toString() {
diff --git a/src/main/java/org/apache/commons/io/filefilter/WildcardFilter.java b/src/main/java/org/apache/commons/io/filefilter/WildcardFilter.java
index e435101fbd4..517d00da6fe 100644
--- a/src/main/java/org/apache/commons/io/filefilter/WildcardFilter.java
+++ b/src/main/java/org/apache/commons/io/filefilter/WildcardFilter.java
@@ -93,9 +93,9 @@ public class WildcardFilter extends AbstractFileFilter implements Serializable {
/**
* Constructs a new case-sensitive wildcard filter for a list of wildcards.
*
- * @param wildcards the list of wildcards to match
- * @throws NullPointerException if the pattern list is null
- * @throws ClassCastException if the list does not contain Strings
+ * @param wildcards The list of wildcards to match.
+ * @throws NullPointerException if the pattern list is null.
+ * @throws ClassCastException if the list does not contain Strings.
*/
public WildcardFilter(final List wildcards) {
Objects.requireNonNull(wildcards, "wildcards");
@@ -105,8 +105,8 @@ public WildcardFilter(final List wildcards) {
/**
* Constructs a new case-sensitive wildcard filter for a single wildcard.
*
- * @param wildcard the wildcard to match
- * @throws NullPointerException if the pattern is null
+ * @param wildcard The wildcard to match.
+ * @throws NullPointerException if the pattern is null.
*/
public WildcardFilter(final String wildcard) {
Objects.requireNonNull(wildcard, "wildcard");
@@ -116,8 +116,8 @@ public WildcardFilter(final String wildcard) {
/**
* Constructs a new case-sensitive wildcard filter for an array of wildcards.
*
- * @param wildcards the array of wildcards to match
- * @throws NullPointerException if the pattern array is null
+ * @param wildcards The array of wildcards to match.
+ * @throws NullPointerException if the pattern array is null.
*/
public WildcardFilter(final String... wildcards) {
Objects.requireNonNull(wildcards, "wildcards");
@@ -127,8 +127,8 @@ public WildcardFilter(final String... wildcards) {
/**
* Tests to see if the file name matches one of the wildcards.
*
- * @param file the file to check
- * @return true if the file name matches one of the wildcards
+ * @param file The file to check.
+ * @return true if the file name matches one of the wildcards.
*/
@Override
public boolean accept(final File file) {
@@ -141,9 +141,9 @@ public boolean accept(final File file) {
/**
* Tests to see if the file name matches one of the wildcards.
*
- * @param dir the file directory
- * @param name the file name
- * @return true if the file name matches one of the wildcards
+ * @param dir The file directory.
+ * @param name The file name.
+ * @return true if the file name matches one of the wildcards.
*/
@Override
public boolean accept(final File dir, final String name) {
@@ -156,9 +156,9 @@ public boolean accept(final File dir, final String name) {
/**
* Tests to see if the file name matches one of the wildcards.
*
- * @param path the file to check
- * @param attributes the path's basic attributes (may be null).
- * @return true if the file name matches one of the wildcards
+ * @param path The file to check.
+ * @param attributes The path's basic attributes (may be null).
+ * @return true if the file name matches one of the wildcards.
* @since 2.9.0
*/
@Override
diff --git a/src/main/java/org/apache/commons/io/function/IOBaseStream.java b/src/main/java/org/apache/commons/io/function/IOBaseStream.java
index a48652d4dda..e819aea8b5b 100644
--- a/src/main/java/org/apache/commons/io/function/IOBaseStream.java
+++ b/src/main/java/org/apache/commons/io/function/IOBaseStream.java
@@ -26,9 +26,9 @@
/**
* Like {@link BaseStream} but throws {@link IOException}.
*
- * @param the type of the stream elements.
- * @param the type of the IO stream extending {@code IOBaseStream}.
- * @param the type of the stream extending {@code BaseStream}.
+ * @param The type of the stream elements.
+ * @param The type of the IO stream extending {@code IOBaseStream}.
+ * @param The type of the stream extending {@code BaseStream}.
* @since 2.12.0
*/
public interface IOBaseStream, B extends BaseStream> extends Closeable {
@@ -37,7 +37,7 @@ public interface IOBaseStream, B extends Base
* Constructs a {@link BaseStream} for this instance that throws {@link UncheckedIOException} instead of
* {@link IOException}.
*
- * @return an {@link UncheckedIOException} {@link BaseStream}.
+ * @return An {@link UncheckedIOException} {@link BaseStream}.
*/
@SuppressWarnings("unchecked")
default BaseStream asBaseStream() {
@@ -139,7 +139,7 @@ default S unordered() {
* Implementations may not have anything to unwrap and that behavior is undefined for now.
*
*
- * @return the underlying stream.
+ * @return The underlying stream.
*/
B unwrap();
diff --git a/src/main/java/org/apache/commons/io/function/IOBaseStreamAdapter.java b/src/main/java/org/apache/commons/io/function/IOBaseStreamAdapter.java
index 967b03f6e47..dc5d4b991aa 100644
--- a/src/main/java/org/apache/commons/io/function/IOBaseStreamAdapter.java
+++ b/src/main/java/org/apache/commons/io/function/IOBaseStreamAdapter.java
@@ -25,8 +25,8 @@
*
* Keep package-private for now.
*
- * @param the type of the stream elements.
- * @param the type of the stream extending {@code IOBaseStream}.
+ * @param The type of the stream elements.
+ * @param The type of the stream extending {@code IOBaseStream}.
*/
abstract class IOBaseStreamAdapter, B extends BaseStream> implements IOBaseStream {
@@ -38,7 +38,7 @@ abstract class IOBaseStreamAdapter, B extends
/**
* Constructs an instance.
*
- * @param delegate the delegate.
+ * @param delegate The delegate.
*/
IOBaseStreamAdapter(final B delegate) {
this.delegate = Objects.requireNonNull(delegate, "delegate");
diff --git a/src/main/java/org/apache/commons/io/function/IOBiConsumer.java b/src/main/java/org/apache/commons/io/function/IOBiConsumer.java
index a8e1bdf397d..a31448c018f 100644
--- a/src/main/java/org/apache/commons/io/function/IOBiConsumer.java
+++ b/src/main/java/org/apache/commons/io/function/IOBiConsumer.java
@@ -25,8 +25,8 @@
/**
* Like {@link BiConsumer} but throws {@link IOException}.
*
- * @param the type of the first argument to the operation
- * @param the type of the second argument to the operation
+ * @param The type of the first argument to the operation.
+ * @param The type of the second argument to the operation.
* @see BiConsumer
* @since 2.12.0
*/
@@ -36,8 +36,8 @@ public interface IOBiConsumer {
/**
* Returns the no-op singleton.
*
- * @param the type of the first argument to the operation
- * @param the type of the second argument to the operation
+ * @param The type of the first argument to the operation.
+ * @param The type of the second argument to the operation.
* @return The no-op singleton.
*/
@SuppressWarnings("unchecked")
@@ -48,8 +48,8 @@ static IOBiConsumer noop() {
/**
* Performs this operation on the given arguments.
*
- * @param t the first input argument
- * @param u the second input argument
+ * @param t The first input argument.
+ * @param u The second input argument.
* @throws IOException if an I/O error occurs.
*/
void accept(T t, U u) throws IOException;
@@ -59,10 +59,10 @@ static IOBiConsumer noop() {
* operation. If performing either operation throws an exception, it is relayed to the caller of the composed operation.
* If performing this operation throws an exception, the {@code after} operation will not be performed.
*
- * @param after the operation to perform after this operation
- * @return a composed {@link IOBiConsumer} that performs in sequence this operation followed by the {@code after}
- * operation
- * @throws NullPointerException if {@code after} is null
+ * @param after The operation to perform after this operation.
+ * @return A composed {@link IOBiConsumer} that performs in sequence this operation followed by the {@code after}
+ * operation.
+ * @throws NullPointerException if {@code after} is null.
*/
default IOBiConsumer andThen(final IOBiConsumer super T, ? super U> after) {
Objects.requireNonNull(after);
@@ -76,7 +76,7 @@ default IOBiConsumer andThen(final IOBiConsumer super T, ? super U> afte
* Creates a {@link BiConsumer} for this instance that throws {@link UncheckedIOException} instead of
* {@link IOException}.
*
- * @return an UncheckedIOException BiConsumer.
+ * @return An UncheckedIOException BiConsumer.
* @throws UncheckedIOException Wraps an {@link IOException}.
* @since 2.12.0
*/
diff --git a/src/main/java/org/apache/commons/io/function/IOBiFunction.java b/src/main/java/org/apache/commons/io/function/IOBiFunction.java
index a72b73f3581..5bdec622565 100644
--- a/src/main/java/org/apache/commons/io/function/IOBiFunction.java
+++ b/src/main/java/org/apache/commons/io/function/IOBiFunction.java
@@ -30,9 +30,9 @@
* {@link #apply(Object, Object)}.
*
*
- * @param the type of the first argument to the function
- * @param the type of the second argument to the function
- * @param the type of the result of the function
+ * @param The type of the first argument to the function.
+ * @param The type of the second argument to the function.
+ * @param The type of the result of the function.
* @see BiFunction
* @since 2.12.0
*/
@@ -44,10 +44,10 @@ public interface IOBiFunction {
* function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the
* composed function.
*
- * @param the type of output of the {@code after} function, and of the composed function
- * @param after the function to apply after this function is applied
- * @return a composed function that first applies this function and then applies the {@code after} function
- * @throws NullPointerException if after is null
+ * @param The type of output of the {@code after} function, and of the composed function.
+ * @param after The function to apply after this function is applied.
+ * @return A composed function that first applies this function and then applies the {@code after} function.
+ * @throws NullPointerException if after is null.
*/
default IOBiFunction andThen(final IOFunction super R, ? extends V> after) {
Objects.requireNonNull(after);
@@ -57,9 +57,9 @@ default IOBiFunction andThen(final IOFunction super R, ? extends
/**
* Applies this function to the given arguments.
*
- * @param t the first function argument
- * @param u the second function argument
- * @return the function result
+ * @param t The first function argument.
+ * @param u The second function argument.
+ * @return The function result.
* @throws IOException if an I/O error occurs.
*/
R apply(T t, U u) throws IOException;
@@ -68,7 +68,7 @@ default IOBiFunction andThen(final IOFunction super R, ? extends
* Creates a {@link BiFunction} for this instance that throws {@link UncheckedIOException} instead of
* {@link IOException}.
*
- * @return an UncheckedIOException BiFunction.
+ * @return An UncheckedIOException BiFunction.
*/
default BiFunction asBiFunction() {
return (t, u) -> Uncheck.apply(this, t, u);
diff --git a/src/main/java/org/apache/commons/io/function/IOBinaryOperator.java b/src/main/java/org/apache/commons/io/function/IOBinaryOperator.java
index d3be4218177..d80d5274918 100644
--- a/src/main/java/org/apache/commons/io/function/IOBinaryOperator.java
+++ b/src/main/java/org/apache/commons/io/function/IOBinaryOperator.java
@@ -25,7 +25,7 @@
/**
* Like {@link BinaryOperator} but throws {@link IOException}.
*
- * @param the type of the operands and result of the operator.
+ * @param The type of the operands and result of the operator.
* @see IOBiFunction
* @see BinaryOperator
* @since 2.12.0
@@ -37,11 +37,11 @@ public interface IOBinaryOperator extends IOBiFunction {
* Creates a {@link IOBinaryOperator} which returns the greater of two elements according to the specified
* {@code Comparator}.
*
- * @param the type of the input arguments of the comparator
- * @param comparator a {@code Comparator} for comparing the two values
- * @return a {@code BinaryOperator} which returns the greater of its operands, according to the supplied
+ * @param The type of the input arguments of the comparator.
+ * @param comparator A {@code Comparator} for comparing the two values.
+ * @return A {@code BinaryOperator} which returns the greater of its operands, according to the supplied
* {@code Comparator}
- * @throws NullPointerException if the argument is null
+ * @throws NullPointerException if the argument is null.
*/
static IOBinaryOperator maxBy(final IOComparator super T> comparator) {
Objects.requireNonNull(comparator);
@@ -52,11 +52,11 @@ static IOBinaryOperator maxBy(final IOComparator super T> comparator) {
* Creates a {@link IOBinaryOperator} which returns the lesser of two elements according to the specified
* {@code Comparator}.
*
- * @param the type of the input arguments of the comparator
- * @param comparator a {@code Comparator} for comparing the two values
- * @return a {@code BinaryOperator} which returns the lesser of its operands, according to the supplied
+ * @param The type of the input arguments of the comparator.
+ * @param comparator A {@code Comparator} for comparing the two values.
+ * @return A {@code BinaryOperator} which returns the lesser of its operands, according to the supplied
* {@code Comparator}
- * @throws NullPointerException if the argument is null
+ * @throws NullPointerException if the argument is null.
*/
static IOBinaryOperator minBy(final IOComparator super T> comparator) {
Objects.requireNonNull(comparator);
@@ -67,7 +67,7 @@ static IOBinaryOperator minBy(final IOComparator super T> comparator) {
* Creates a {@link BinaryOperator} for this instance that throws {@link UncheckedIOException} instead of
* {@link IOException}.
*
- * @return an unchecked BiFunction.
+ * @return An unchecked BiFunction.
*/
default BinaryOperator asBinaryOperator() {
return (t, u) -> Uncheck.apply(this, t, u);
diff --git a/src/main/java/org/apache/commons/io/function/IOBooleanSupplier.java b/src/main/java/org/apache/commons/io/function/IOBooleanSupplier.java
index 0b8b1dcfd8b..ed9bb80a8f6 100644
--- a/src/main/java/org/apache/commons/io/function/IOBooleanSupplier.java
+++ b/src/main/java/org/apache/commons/io/function/IOBooleanSupplier.java
@@ -33,7 +33,7 @@ public interface IOBooleanSupplier {
/**
* Creates a {@link Supplier} for this instance that throws {@link UncheckedIOException} instead of {@link IOException}.
*
- * @return an UncheckedIOException Supplier.
+ * @return An UncheckedIOException Supplier.
*/
default BooleanSupplier asBooleanSupplier() {
return () -> Uncheck.getAsBoolean(this);
@@ -42,7 +42,7 @@ default BooleanSupplier asBooleanSupplier() {
/**
* Gets a result.
*
- * @return a result
+ * @return A result.
* @throws IOException if an I/O error occurs.
*/
boolean getAsBoolean() throws IOException;
diff --git a/src/main/java/org/apache/commons/io/function/IOComparator.java b/src/main/java/org/apache/commons/io/function/IOComparator.java
index eb31ef818ef..e1600718ac5 100644
--- a/src/main/java/org/apache/commons/io/function/IOComparator.java
+++ b/src/main/java/org/apache/commons/io/function/IOComparator.java
@@ -24,7 +24,7 @@
/**
* Like {@link Comparator} but throws {@link IOException}.
*
- * @param the type of objects that may be compared by this comparator
+ * @param The type of objects that may be compared by this comparator.
* @see Comparator
* @since 2.12.0
*/
@@ -35,7 +35,7 @@ public interface IOComparator {
* Creates a {@link Comparator} for this instance that throws {@link UncheckedIOException} instead of
* {@link IOException}.
*
- * @return an UncheckedIOException BiFunction.
+ * @return An UncheckedIOException BiFunction.
*/
default Comparator asComparator() {
return (t, u) -> Uncheck.compare(this, t, u);
@@ -44,11 +44,11 @@ default Comparator asComparator() {
/**
* Like {@link Comparator#compare(Object, Object)} but throws {@link IOException}.
*
- * @param o1 the first object to be compared.
- * @param o2 the second object to be compared.
- * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than
+ * @param o1 The first object to be compared.
+ * @param o2 The second object to be compared.
+ * @return A negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than
* the second.
- * @throws NullPointerException if an argument is null and this comparator does not permit null arguments
+ * @throws NullPointerException if an argument is null and this comparator does not permit null arguments.
* @throws ClassCastException if the arguments' types prevent them from being compared by this comparator.
* @throws IOException if an I/O error occurs.
*/
diff --git a/src/main/java/org/apache/commons/io/function/IOConsumer.java b/src/main/java/org/apache/commons/io/function/IOConsumer.java
index 016b643f95f..7521cac8cc2 100644
--- a/src/main/java/org/apache/commons/io/function/IOConsumer.java
+++ b/src/main/java/org/apache/commons/io/function/IOConsumer.java
@@ -29,7 +29,7 @@
/**
* Like {@link Consumer} but throws {@link IOException}.
*
- * @param the type of the input to the operations.
+ * @param The type of the input to the operations.
* @since 2.7
*/
@FunctionalInterface
@@ -42,6 +42,21 @@ public interface IOConsumer {
// noop
};
+ /**
+ * Applies the given {@link IOConsumer} action to the object if the consumer is not {@code null}. Otherwise, does nothing.
+ *
+ * @param consumer The consumer to consume.
+ * @param object The object to be consumed.
+ * @param the type of the argument the consumer accepts.
+ * @throws IOException Thrown when the consumer fails.
+ * @since 2.23.0
+ */
+ static void accept(final IOConsumer consumer, final T object) throws IOException {
+ if (consumer != null) {
+ consumer.accept(object);
+ }
+ }
+
/**
* Performs an action for each element of the collection gathering any exceptions.
*
@@ -125,7 +140,7 @@ static void forEach(final T[] array, final IOConsumer action) throws IOEx
* Returns the constant no-op consumer.
*
* @param Type consumer type.
- * @return a constant no-op consumer.
+ * @return A constant no-op consumer.
* @since 2.9.0
*/
@SuppressWarnings("unchecked")
@@ -136,7 +151,7 @@ static IOConsumer noop() {
/**
* Performs this operation on the given argument.
*
- * @param t the input argument
+ * @param t The input argument.
* @throws IOException if an I/O error occurs.
*/
void accept(T t) throws IOException;
@@ -146,9 +161,9 @@ static IOConsumer noop() {
* operation. If performing either operation throws an exception, it is relayed to the caller of the composed operation.
* If performing this operation throws an exception, the {@code after} operation will not be performed.
*
- * @param after the operation to perform after this operation
- * @return a composed {@link Consumer} that performs in sequence this operation followed by the {@code after} operation
- * @throws NullPointerException if {@code after} is null
+ * @param after The operation to perform after this operation.
+ * @return A composed {@link Consumer} that performs in sequence this operation followed by the {@code after} operation.
+ * @throws NullPointerException if {@code after} is null.
*/
default IOConsumer andThen(final IOConsumer super T> after) {
Objects.requireNonNull(after, "after");
@@ -161,7 +176,7 @@ default IOConsumer andThen(final IOConsumer super T> after) {
/**
* Creates a {@link Consumer} for this instance that throws {@link UncheckedIOException} instead of {@link IOException}.
*
- * @return an UncheckedIOException Consumer.
+ * @return An UncheckedIOException Consumer.
* @since 2.12.0
*/
default Consumer asConsumer() {
diff --git a/src/main/java/org/apache/commons/io/function/IOFunction.java b/src/main/java/org/apache/commons/io/function/IOFunction.java
index 07e9d539a99..c28760d0e4b 100644
--- a/src/main/java/org/apache/commons/io/function/IOFunction.java
+++ b/src/main/java/org/apache/commons/io/function/IOFunction.java
@@ -27,8 +27,8 @@
/**
* Like {@link Function} but throws {@link IOException}.
*
- * @param the type of the input to the operations.
- * @param the return type of the operations.
+ * @param The type of the input to the operations.
+ * @param The return type of the operations.
* @since 2.7
*/
@FunctionalInterface
@@ -37,8 +37,8 @@ public interface IOFunction {
/**
* Returns a {@link IOFunction} that always returns its input argument.
*
- * @param the type of the input and output objects to the function
- * @return a function that always returns its input argument
+ * @param The type of the input and output objects to the function.
+ * @return A function that always returns its input argument.
*/
@SuppressWarnings("unchecked")
static IOFunction identity() {
@@ -50,9 +50,9 @@ static IOFunction identity() {
* {@code after} consumer to the result. If evaluation of either function throws an exception, it is relayed to the
* caller of the composed function.
*
- * @param after the consumer to apply after this function is applied
- * @return a composed function that first applies this function and then applies the {@code after} consumer
- * @throws NullPointerException if after is null
+ * @param after The consumer to apply after this function is applied.
+ * @return A composed function that first applies this function and then applies the {@code after} consumer.
+ * @throws NullPointerException if after is null.
* @see #compose(IOFunction)
*/
default IOConsumer andThen(final Consumer super R> after) {
@@ -65,10 +65,10 @@ default IOConsumer andThen(final Consumer super R> after) {
* {@code after} function to the result. If evaluation of either function throws an exception, it is relayed to the
* caller of the composed function.
*
- * @param the type of output of the {@code after} function, and of the composed function
- * @param after the function to apply after this function is applied
- * @return a composed function that first applies this function and then applies the {@code after} function
- * @throws NullPointerException if after is null
+ * @param The type of output of the {@code after} function, and of the composed function.
+ * @param after The function to apply after this function is applied.
+ * @return A composed function that first applies this function and then applies the {@code after} function.
+ * @throws NullPointerException if after is null.
* @see #compose(IOFunction)
*/
default IOFunction andThen(final Function super R, ? extends V> after) {
@@ -81,9 +81,9 @@ default IOFunction andThen(final Function super R, ? extends V> afte
* {@code after} consumer to the result. If evaluation of either function throws an exception, it is relayed to the
* caller of the composed function.
*
- * @param after the consumer to apply after this function is applied
- * @return a composed function that first applies this function and then applies the {@code after} consumer
- * @throws NullPointerException if after is null
+ * @param after The consumer to apply after this function is applied.
+ * @return A composed function that first applies this function and then applies the {@code after} consumer.
+ * @throws NullPointerException if after is null.
* @see #compose(IOFunction)
*/
default IOConsumer andThen(final IOConsumer super R> after) {
@@ -96,10 +96,10 @@ default IOConsumer andThen(final IOConsumer super R> after) {
* {@code after} function to the result. If evaluation of either function throws an exception, it is relayed to the
* caller of the composed function.
*
- * @param the type of output of the {@code after} function, and of the composed function
- * @param after the function to apply after this function is applied
- * @return a composed function that first applies this function and then applies the {@code after} function
- * @throws NullPointerException if after is null
+ * @param The type of output of the {@code after} function, and of the composed function.
+ * @param after The function to apply after this function is applied.
+ * @return A composed function that first applies this function and then applies the {@code after} function.
+ * @throws NullPointerException if after is null.
* @see #compose(IOFunction)
*/
default IOFunction andThen(final IOFunction super R, ? extends V> after) {
@@ -110,8 +110,8 @@ default IOFunction andThen(final IOFunction super R, ? extends V> af
/**
* Applies this function to the given argument.
*
- * @param t the function argument
- * @return the function result
+ * @param t The function argument.
+ * @return The function result.
* @throws IOException if an I/O error occurs.
*/
R apply(T t) throws IOException;
@@ -119,7 +119,7 @@ default IOFunction andThen(final IOFunction super R, ? extends V> af
/**
* Creates a {@link Function} for this instance that throws {@link UncheckedIOException} instead of {@link IOException}.
*
- * @return an UncheckedIOException Function.
+ * @return An UncheckedIOException Function.
* @since 2.12.0
*/
default Function asFunction() {
@@ -131,10 +131,10 @@ default Function asFunction() {
* this function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the
* composed function.
*
- * @param the type of input to the {@code before} function, and to the composed function
- * @param before the function to apply before this function is applied
- * @return a composed function that first applies the {@code before} function and then applies this function
- * @throws NullPointerException if before is null
+ * @param The type of input to the {@code before} function, and to the composed function.
+ * @param before The function to apply before this function is applied.
+ * @return A composed function that first applies the {@code before} function and then applies this function.
+ * @throws NullPointerException if before is null.
* @see #andThen(IOFunction)
*/
default IOFunction compose(final Function super V, ? extends T> before) {
@@ -147,10 +147,10 @@ default IOFunction compose(final Function super V, ? extends T> befo
* this function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the
* composed function.
*
- * @param the type of input to the {@code before} function, and to the composed function
- * @param before the function to apply before this function is applied
- * @return a composed function that first applies the {@code before} function and then applies this function
- * @throws NullPointerException if before is null
+ * @param The type of input to the {@code before} function, and to the composed function.
+ * @param before The function to apply before this function is applied.
+ * @return A composed function that first applies the {@code before} function and then applies this function.
+ * @throws NullPointerException if before is null.
* @see #andThen(IOFunction)
*/
default IOFunction compose(final IOFunction super V, ? extends T> before) {
@@ -163,9 +163,9 @@ default IOFunction compose(final IOFunction super V, ? extends T> be
* this function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the
* composed function.
*
- * @param before the supplier which feeds the application of this function
- * @return a composed function that first applies the {@code before} function and then applies this function
- * @throws NullPointerException if before is null
+ * @param before The supplier which feeds the application of this function.
+ * @return A composed function that first applies the {@code before} function and then applies this function.
+ * @throws NullPointerException if before is null.
* @see #andThen(IOFunction)
*/
default IOSupplier compose(final IOSupplier extends T> before) {
@@ -178,9 +178,9 @@ default IOSupplier compose(final IOSupplier extends T> before) {
* this function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the
* composed function.
*
- * @param before the supplier which feeds the application of this function
- * @return a composed function that first applies the {@code before} function and then applies this function
- * @throws NullPointerException if before is null
+ * @param before The supplier which feeds the application of this function.
+ * @return A composed function that first applies the {@code before} function and then applies this function.
+ * @throws NullPointerException if before is null.
* @see #andThen(IOFunction)
*/
default IOSupplier compose(final Supplier extends T> before) {
diff --git a/src/main/java/org/apache/commons/io/function/IOIntConsumer.java b/src/main/java/org/apache/commons/io/function/IOIntConsumer.java
index 9c45b29a011..a473a577bc4 100644
--- a/src/main/java/org/apache/commons/io/function/IOIntConsumer.java
+++ b/src/main/java/org/apache/commons/io/function/IOIntConsumer.java
@@ -41,7 +41,7 @@ public interface IOIntConsumer {
/**
* Performs this operation on the given argument.
*
- * @param value the input argument
+ * @param value The input argument.
* @throws IOException if an I/O error occurs.
*/
void accept(int value) throws IOException;
@@ -51,9 +51,9 @@ public interface IOIntConsumer {
* operation throws an exception, it is relayed to the caller of the composed operation. If performing this operation throws an exception, the {@code after}
* operation will not be performed.
*
- * @param after the operation to perform after this operation
- * @return a composed {@code IOIntConsumer} that performs in sequence this operation followed by the {@code after} operation
- * @throws NullPointerException if {@code after} is null
+ * @param after The operation to perform after this operation.
+ * @return A composed {@code IOIntConsumer} that performs in sequence this operation followed by the {@code after} operation.
+ * @throws NullPointerException if {@code after} is null.
*/
default IOIntConsumer andThen(final IOIntConsumer after) {
Objects.requireNonNull(after);
@@ -66,7 +66,7 @@ default IOIntConsumer andThen(final IOIntConsumer after) {
/**
* Creates a {@link Consumer} for this instance that throws {@link UncheckedIOException} instead of {@link IOException}.
*
- * @return an UncheckedIOException IntConsumer.
+ * @return An UncheckedIOException IntConsumer.
*/
default Consumer asConsumer() {
return i -> Uncheck.accept(this, i);
@@ -75,7 +75,7 @@ default Consumer asConsumer() {
/**
* Creates an {@link IntConsumer} for this instance that throws {@link UncheckedIOException} instead of {@link IOException}.
*
- * @return an UncheckedIOException IntConsumer.
+ * @return An UncheckedIOException IntConsumer.
*/
default IntConsumer asIntConsumer() {
return i -> Uncheck.accept(this, i);
diff --git a/src/main/java/org/apache/commons/io/function/IOIntSupplier.java b/src/main/java/org/apache/commons/io/function/IOIntSupplier.java
index 02e770cc3a3..abadfdd22c3 100644
--- a/src/main/java/org/apache/commons/io/function/IOIntSupplier.java
+++ b/src/main/java/org/apache/commons/io/function/IOIntSupplier.java
@@ -33,7 +33,7 @@ public interface IOIntSupplier {
/**
* Creates a {@link Supplier} for this instance that throws {@link UncheckedIOException} instead of {@link IOException}.
*
- * @return an UncheckedIOException Supplier.
+ * @return An UncheckedIOException Supplier.
*/
default IntSupplier asIntSupplier() {
return () -> Uncheck.getAsInt(this);
@@ -42,7 +42,7 @@ default IntSupplier asIntSupplier() {
/**
* Gets a result.
*
- * @return a result
+ * @return A result.
* @throws IOException if an I/O error occurs.
*/
int getAsInt() throws IOException;
diff --git a/src/main/java/org/apache/commons/io/function/IOIterable.java b/src/main/java/org/apache/commons/io/function/IOIterable.java
index 238040d1d65..ddc4c4fb72c 100644
--- a/src/main/java/org/apache/commons/io/function/IOIterable.java
+++ b/src/main/java/org/apache/commons/io/function/IOIterable.java
@@ -24,7 +24,7 @@
/**
* Like {@link Iterable} but throws {@link IOException}.
*
- * @param the type of elements returned by the iterable.
+ * @param The type of elements returned by the iterable.
* @since 2.19.0
*/
public interface IOIterable {
@@ -33,7 +33,7 @@ public interface IOIterable {
* Creates an {@link Iterable} for this instance that throws {@link UncheckedIOException} instead of
* {@link IOException}.
*
- * @return an {@link UncheckedIOException} {@link Iterable}.
+ * @return An {@link UncheckedIOException} {@link Iterable}.
* @since 2.21.0
*/
default Iterable asIterable() {
@@ -44,8 +44,8 @@ default Iterable asIterable() {
* Like {@link Iterable#iterator()}.
*
* @param action The action to be performed for each element.
- * @throws NullPointerException if the specified action is null.
- * @throws IOException thrown by the given action.
+ * @throws NullPointerException Thrown if the specified action is null.
+ * @throws IOException Thrown if an I/O error occurs for a remaining element, or the given action throws.
* @see Iterable#iterator()
*/
default void forEach(final IOConsumer super T> action) throws IOException {
@@ -75,7 +75,8 @@ default IOSpliterator spliterator() {
*
* Implementations may not have anything to unwrap and that behavior is undefined for now.
*
- * @return the underlying Iterable.
+ *
+ * @return The underlying Iterable.
*/
Iterable unwrap();
diff --git a/src/main/java/org/apache/commons/io/function/IOIterator.java b/src/main/java/org/apache/commons/io/function/IOIterator.java
index 42cc235fc39..6008e655adc 100644
--- a/src/main/java/org/apache/commons/io/function/IOIterator.java
+++ b/src/main/java/org/apache/commons/io/function/IOIterator.java
@@ -27,7 +27,7 @@
/**
* Like {@link Iterator} but throws {@link IOException}.
*
- * @param the type of elements returned by this iterator.
+ * @param The type of elements returned by this iterator.
* @since 2.12.0
*/
public interface IOIterator {
@@ -35,9 +35,9 @@ public interface IOIterator {
/**
* Adapts the given Iterable as an IOIterator.
*
- * @param the type of the stream elements.
- * @param iterable The iterable to adapt
- * @return A new IOIterator
+ * @param The type of the stream elements.
+ * @param iterable The iterable to adapt.
+ * @return A new IOIterator.
* @since 2.17.0
*/
static IOIterator adapt(final Iterable iterable) {
@@ -47,9 +47,9 @@ static IOIterator adapt(final Iterable iterable) {
/**
* Adapts the given Iterator as an IOIterator.
*
- * @param the type of the stream elements.
- * @param iterator The iterator to adapt
- * @return A new IOIterator
+ * @param The type of the stream elements.
+ * @param iterator The iterator to adapt.
+ * @return A new IOIterator.
*/
static IOIterator adapt(final Iterator iterator) {
return IOIteratorAdapter.adapt(iterator);
@@ -59,7 +59,7 @@ static IOIterator adapt(final Iterator iterator) {
* Creates an {@link Iterator} for this instance that throws {@link UncheckedIOException} instead of
* {@link IOException}.
*
- * @return an {@link UncheckedIOException} {@link Iterator}.
+ * @return An {@link UncheckedIOException} {@link Iterator}.
*/
default Iterator asIterator() {
return new UncheckedIOIterator<>(this);
@@ -91,7 +91,7 @@ default void forEachRemaining(final IOConsumer super E> action) throws IOExcep
*
* @return See delegate.
* @throws IOException if an I/O error occurs.
- * @throws NoSuchElementException if the iteration has no more elements
+ * @throws NoSuchElementException if the iteration has no more elements.
*/
E next() throws IOException;
@@ -110,7 +110,8 @@ default void remove() throws IOException {
*
* Implementations may not have anything to unwrap and that behavior is undefined for now.
*
- * @return the underlying Iterator.
+ *
+ * @return The underlying Iterator.
*/
Iterator unwrap();
diff --git a/src/main/java/org/apache/commons/io/function/IOIteratorAdapter.java b/src/main/java/org/apache/commons/io/function/IOIteratorAdapter.java
index 7a11c8e1449..14735803d55 100644
--- a/src/main/java/org/apache/commons/io/function/IOIteratorAdapter.java
+++ b/src/main/java/org/apache/commons/io/function/IOIteratorAdapter.java
@@ -24,7 +24,7 @@
/**
* Adapts an {@link Iterator} as an {@link IOIterator}.
*
- * @param the type of the stream elements.
+ * @param The type of the stream elements.
*/
final class IOIteratorAdapter implements IOIterator {
diff --git a/src/main/java/org/apache/commons/io/function/IOLongSupplier.java b/src/main/java/org/apache/commons/io/function/IOLongSupplier.java
index 8e90866273c..563f7585a0b 100644
--- a/src/main/java/org/apache/commons/io/function/IOLongSupplier.java
+++ b/src/main/java/org/apache/commons/io/function/IOLongSupplier.java
@@ -33,7 +33,7 @@ public interface IOLongSupplier {
/**
* Creates a {@link Supplier} for this instance that throws {@link UncheckedIOException} instead of {@link IOException}.
*
- * @return an UncheckedIOException Supplier.
+ * @return An UncheckedIOException Supplier.
*/
default LongSupplier asSupplier() {
return () -> Uncheck.getAsLong(this);
@@ -42,7 +42,7 @@ default LongSupplier asSupplier() {
/**
* Gets a result.
*
- * @return a result
+ * @return A result.
* @throws IOException if an I/O error occurs.
*/
long getAsLong() throws IOException;
diff --git a/src/main/java/org/apache/commons/io/function/IOPredicate.java b/src/main/java/org/apache/commons/io/function/IOPredicate.java
index fda3fddb6be..b2ea6e2c059 100644
--- a/src/main/java/org/apache/commons/io/function/IOPredicate.java
+++ b/src/main/java/org/apache/commons/io/function/IOPredicate.java
@@ -25,7 +25,7 @@
/**
* Like {@link Predicate} but throws {@link IOException}.
*
- * @param the type of the input to the predicate
+ * @param The type of the input to the predicate.
* @since 2.12.0
*/
@FunctionalInterface
@@ -34,8 +34,8 @@ public interface IOPredicate {
/**
* Always false.
*
- * @param the type of the input to the predicate
- * @return a constant predicate that tests always false.
+ * @param The type of the input to the predicate.
+ * @return A constant predicate that tests always false.
*/
@SuppressWarnings("unchecked")
static IOPredicate alwaysFalse() {
@@ -45,8 +45,8 @@ static IOPredicate alwaysFalse() {
/**
* Always true.
*
- * @param the type of the input to the predicate
- * @return a constant predicate that tests always true.
+ * @param The type of the input to the predicate.
+ * @return A constant predicate that tests always true.
*/
@SuppressWarnings("unchecked")
static IOPredicate alwaysTrue() {
@@ -56,12 +56,12 @@ static IOPredicate alwaysTrue() {
/**
* Creates a predicate that tests if two arguments are equal using {@link Objects#equals(Object, Object)}.
*
- * @param the type of arguments to the predicate
- * @param target the object to compare for equality, may be {@code null}
- * @return a predicate that tests if two arguments are equal using {@link Objects#equals(Object, Object)}
+ * @param The type of arguments to the predicate.
+ * @param target The object to compare for equality, may be {@code null}
+ * @return A predicate that tests if two arguments are equal using {@link Objects#equals(Object, Object)}
*/
static IOPredicate isEqual(final Object target) {
- return null == target ? Objects::isNull : object -> target.equals(object);
+ return target == null ? Objects::isNull : object -> target.equals(object);
}
/**
@@ -74,10 +74,10 @@ static IOPredicate isEqual(final Object target) {
* predicate throws an exception, the {@code other} predicate will not be evaluated.
*
*
- * @param other a predicate that will be logically-ANDed with this predicate
- * @return a composed predicate that represents the short-circuiting logical AND of this predicate and the {@code other}
- * predicate
- * @throws NullPointerException if other is null
+ * @param other A predicate that will be logically-ANDed with this predicate.
+ * @return A composed predicate that represents the short-circuiting logical AND of this predicate and the {@code other}
+ * predicate.
+ * @throws NullPointerException if other is null.
*/
default IOPredicate and(final IOPredicate super T> other) {
Objects.requireNonNull(other);
@@ -88,7 +88,7 @@ default IOPredicate and(final IOPredicate super T> other) {
* Creates a {@link Predicate} for this instance that throws {@link UncheckedIOException} instead of
* {@link IOException}.
*
- * @return an UncheckedIOException Predicate.
+ * @return An UncheckedIOException Predicate.
*/
default Predicate asPredicate() {
return t -> Uncheck.test(this, t);
@@ -97,7 +97,7 @@ default Predicate asPredicate() {
/**
* Creates a predicate that represents the logical negation of this predicate.
*
- * @return a predicate that represents the logical negation of this predicate
+ * @return A predicate that represents the logical negation of this predicate.
*/
default IOPredicate negate() {
return t -> !test(t);
@@ -113,10 +113,10 @@ default IOPredicate negate() {
* predicate throws an exception, the {@code other} predicate will not be evaluated.
*
*
- * @param other a predicate that will be logically-ORed with this predicate
- * @return a composed predicate that represents the short-circuiting logical OR of this predicate and the {@code other}
- * predicate
- * @throws NullPointerException if other is null
+ * @param other A predicate that will be logically-ORed with this predicate.
+ * @return A composed predicate that represents the short-circuiting logical OR of this predicate and the {@code other}
+ * predicate.
+ * @throws NullPointerException if other is null.
*/
default IOPredicate or(final IOPredicate super T> other) {
Objects.requireNonNull(other);
@@ -126,7 +126,7 @@ default IOPredicate or(final IOPredicate super T> other) {
/**
* Evaluates this predicate on the given argument.
*
- * @param t the input argument
+ * @param t The input argument.
* @return {@code true} if the input argument matches the predicate, otherwise {@code false}
* @throws IOException if an I/O error occurs.
*/
diff --git a/src/main/java/org/apache/commons/io/function/IOQuadFunction.java b/src/main/java/org/apache/commons/io/function/IOQuadFunction.java
index 78db4284b67..987985cce95 100644
--- a/src/main/java/org/apache/commons/io/function/IOQuadFunction.java
+++ b/src/main/java/org/apache/commons/io/function/IOQuadFunction.java
@@ -29,11 +29,11 @@
* {@link #apply(Object, Object, Object, Object)}.
*
*
- * @param the type of the first argument to the function
- * @param the type of the second argument to the function
- * @param the type of the third argument to the function
- * @param the type of the fourth argument to the function
- * @param the type of the result of the function
+ * @param The type of the first argument to the function.
+ * @param The type of the second argument to the function.
+ * @param The type of the third argument to the function.
+ * @param The type of the fourth argument to the function.
+ * @param The type of the result of the function.
* @see Function
* @since 2.12.0
*/
@@ -45,10 +45,10 @@ public interface IOQuadFunction {
* function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the
* composed function.
*
- * @param the type of output of the {@code after} function, and of the composed function
- * @param after the function to apply after this function is applied
- * @return a composed function that first applies this function and then applies the {@code after} function
- * @throws NullPointerException if after is null
+ * @param