DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Java Is Greener on Arm
  • Mastering Date/Time APIs: Challenges With Java's Calendar and JDK Date/Time APIs
  • Java 23: What Developers Need to Know

Trending

  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 1
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • Building Resilient Networks: Limiting the Risk and Scope of Cyber Attacks
  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  1. DZone
  2. Coding
  3. Java
  4. Transferring InputStream to OutputStream in JDK 9

Transferring InputStream to OutputStream in JDK 9

Java 9 added a simple method to help transfer InputStreams to OutputStreams. Let's see how it works and a few community concerns with it.

By 
Dustin Marx user avatar
Dustin Marx
·
Feb. 01, 18 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
32.0K Views

Join the DZone community and get the full member experience.

Join For Free

One of the minor additions to JDK 9 that can make a sometimes routine task in Java even easier is the addition of the method InputStream.transferTo(OutputStream). This method, as its name suggests, allows for the easy transfer (copy) of bytes from the input stream represented by the object the method is called upon to the output stream provided to that method. Or, as the method's Javadoc comment states, InputStream.transferTo(OutputStream) "reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read."

There is more to the Javadoc comment on the InputStream.transferTo(OutputStream) method including these statements:

  • "This method does not close either stream."
  • "It is strongly recommended that both streams be promptly closed if an I/O error occurs."

The easiest way to deal with the two concerns shown above that are expressed in the Javadoc comment for the InputStream.transferTo(OutputStream) method is to instantiate both the source InputStream and the target OutputStream in a try-with-resources statement. An example of this is shown in the next code listing.

StreamsTransfer.java: Using InputStream.transferTo(OutputStream)

package dustin.examples.iostreams;

import static java.lang.System.out;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Demonstrate InputStream.transferTo(OutputStream) added in JDK 9.
*/
public class StreamsTransfer
{
    /**
     * Demonstrate use of InputStream.transferTo(OutputStream) using
     * FileInputStream and FileOutputStream implementations of
     * InputStream and OutputStream respectively.
     *
     * @param arguments Command-line arguments: one expected,
     *    which is the name of the input file.
    */
    public static void main(final String[] arguments)
    {
        if (arguments.length < 1)
        {
            out.println("USAGE StreamsTransfer <fileName>");
            System.exit(-1);
        }
        final String fileName = arguments[0];
        try (final InputStream is = new FileInputStream(fileName);
            final OutputStream os = new FileOutputStream(fileName + ".copy"))
        {
            is.transferTo(os);
        }
        catch (IOException exception)
        {
            out.println("Exception encountered: " + exception);
        }
    }
}


The try-with-resources statement in the above code listing opens the two resources (instances of InputStream and OutputStream) and so ensures that they are always closed. The implementation of InputStream used in this example is FileInputStream and the implementation of OutputStream used in this example is FileOutputStream.

Although the file copying implemented in the above example could be more easily accomplished in Java with a different mechanism (such as using one of the overloaded Files.copy methods), the approach shown in the code listing above is only intended for easy illustration and can be generalized to any implementations of InputStream and OutputStream. For another example, Josh Bloch discusses use of InputStream.transferTo(OutputStream) in Item 59 of Effective Java (Third Edition) and his illustration uses URL.openStream() as the InputStream and System.out as the OutputStream.

When the above example is executed, it will copy the provided file to another file with the same name with ".copy" added to the end of the new file's name. The two I/O streams are closed even if an exception occurs during processing of either one.

The addition of InputStream.transferTo(OutputStream) seems to be generally welcomed among the Java development community. Ali Dehghani talks about this method in the post "Least significant bits of Java 9." This method is also included in the post "5 things made easier in Java 9" (which also points out that effectively final variables can now be used in try-with-resources rather than explicitly making them final like I did in my example). The Reddit /r/java subreddit includes an interesting discussion titled "New method in JDK 9: InputStream.transferTo(OutputStream)."

Not everyone is fan of the adding of InputStream.transferTo(OutputStream) in JDK 9. In the post "Java 9: The Good, The Bad, and Private Interface Methods", Yegor Bugayenko describes InputStream as an "already over bloated class" and writes that the addition of InputStream.transferTo(OutputStream) is "one of the most typical mistakes young OOP programmers are making: they make their interfaces big ... just because they need more functionality." He also points that IOUtils.copy(InputStream, OutputStream) was already available via Apache Commons.

The addition of the InputStream.transferTo(OutputStream) method with JDK 9 is a small but sometimes very handy addition to the standard JDK that is especially easy to use in conjunction with the try-with-resources statement.

Java (programming language) Java Development Kit

Published at DZone with permission of Dustin Marx, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Java Is Greener on Arm
  • Mastering Date/Time APIs: Challenges With Java's Calendar and JDK Date/Time APIs
  • Java 23: What Developers Need to Know

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!