Java nio inputstream to outputstream java

Transferring InputStream to OutputStream in JDK 9

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 "); 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.

Читайте также:  Модуль sys stdin python

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.

Источник

Convert InputStream to OutputStream in Java

Learn to convert or pipe an InputStream to OutputStream in Java using various Java APIs, Commons-IO and Guava libraries.

It is recommended to use the try-with-resources statement with Streams. Else use finally statements to close the streams.

1. Using InputStream.transferTo() [Java 9]

The new method transferTo() , in Java 9, reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read.

It does not close either stream so it is important to close the streams by other means.

try (InputStream inputStream = new ByteArrayInputStream("howtodoinjava".getBytes()); OutputStream outputStream = new ByteArrayOutputStream();) < inputStream.transferTo(outputStream); >catch (IOException e) < //handle exception >

2. Writing Directly in Java 8

There is no API similar to transferTo() in Java 8. So we can mimic the logic written in the above API’s source code and write it ourselves.

void copy(InputStream in, OutputStream out) throws IOException < byte[] buf = new byte[8192]; int length; while ((length = in.read(buf)) >0) < out.write(buf, 0, length); >>

3. Using Guava ByteStreams.copy()

We can use the ByteStreams.copy() API from transferring the bytes from InputStream to OutputStream.

The ByteStreams class contains many utility methods for working with byte arrays and I/O streams. The copy() method copies all bytes from the input stream to the output stream.

It does not close or flush either stream.

try (InputStream inputStream = new ByteArrayInputStream("howtodoinjava".getBytes()); OutputStream outputStream = new ByteArrayOutputStream()) < ByteStreams.copy(inputStream, outputStream); >catch (IOException e) < //handle exception >

4. Using Commons IO’s IOUtils.copy()

The IOUtils class provides static utility methods for input/output operations, including convering between streams.

Its copy() method copies bytes from an InputStream to an OutputStream. This method buffers the input internally, so there is no need to use a BufferedInputStream .

try (InputStream inputStream = new ByteArrayInputStream("howtodoinjava".getBytes()); OutputStream outputStream = new ByteArrayOutputStream()) < IOUtils.copy(inputStream, outputStream); >catch (IOException e) < //handle exception >

For large streams use the copyLarge() method that supports copying large byte array data over 2 GB.

IOUtils.copyLarge(inputStream, outputStream);

In this Java IO tutorial, we learned many easy and handy ways to copy the byte array data from InputStream to OutputStream. We learned to convert small as well as large input streams to output streams.

Источник

Easy Ways to Write a Java InputStream to an OutputStream

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’re going to learn how to write a Java InputStream to a Java OutputStream. We’ll first use core functionality from Java 8 and Java 9. Then, we’ll look at a couple of external libraries — Guava and the Apache Commons IO library.

The utility methods provided by Java 9, Guava, and Apache Commons IO do not flush or close the streams. So, we’ll need to manage these resources by using try-with-resources or a finally block.

2. Using Java 8

First, we’ll begin by creating a simple method using vanilla Java to copy the content from the InputStream to the OutputStream:

void copy(InputStream source, OutputStream target) throws IOException < byte[] buf = new byte[8192]; int length; while ((length = source.read(buf)) != -1) < target.write(buf, 0, length); >>

This code is pretty straightforward — we’re simply reading in some bytes and then writing them out.

3. Using Java 9

Java 9 provides a utility method, InputStream.transferTo(), for this task.

Let’s look at how we would use the transferTo() method:

@Test public void givenUsingJavaNine_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException < String initialString = "Hello World!"; try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes()); ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) < inputStream.transferTo(targetStream); assertEquals(initialString, new String(targetStream.toByteArray())); >>

Note that when working with file streams, it’s more efficient to use Files.copy() than the transferTo() method.

4. Using Guava

Next, let’s look at how we would use Guava’s utility method ByteStreams.copy().

We’ll need to include the guava dependency in our pom.xml:

 com.google.guava guava 31.1-jre 

Let’s create a simple test case to show how we could use ByteStreams to copy data:

@Test public void givenUsingGuava_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException < String initialString = "Hello World!"; try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes()); ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) < ByteStreams.copy(inputStream, targetStream); assertEquals(initialString, new String(targetStream.toByteArray())); >>

5. Using Commons IO

Finally, let’s look at how we would use the Commons IO IOUtils.copy() method for this task.

Of course, we’ll need to add the commons-io dependency to the pom.xml:

Let’s create a simple test case using IOUtils to copy data from the input stream to the output stream:

@Test public void givenUsingCommonsIO_whenCopyingInputStreamToOutputStream_thenCorrect() throws IOException < String initialString = "Hello World!"; try (InputStream inputStream = new ByteArrayInputStream(initialString.getBytes()); ByteArrayOutputStream targetStream = new ByteArrayOutputStream()) < IOUtils.copy(inputStream, targetStream); assertEquals(initialString, new String(targetStream.toByteArray())); >>

Note: Commons IO provides additional methods for working with InputStreams and OutputStreams. IOUtils.copyLarge() should be used whenever it is necessary to copy 2 GB or more of data.

6. Conclusion

In this article, we explored simple ways to copy data from an InputStream to an OutputStream.

The implementation of these examples is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью