- How to Convert an InputStream to a File in Java
- 1. InputStream::transferTo (Java 9)
- 2. Files::copy (Java 7)
- 3. IOUtils::copy (Apache Commons IO)
- 4. FileUtils::copyInputStreamToFile (Apache Commons IO)
- 5. Plain Java (no external libraries)
- Java – Write an InputStream to a File
- Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
- > CHECK OUT THE COURSE
- 1. Overview
- Further reading:
- Java — InputStream to Reader
- Java — Convert File to InputStream
- Java InputStream to Byte Array and ByteBuffer
- 2. Convert Using Plain Java
- 3. Convert Using Guava
- 4. Convert Using Commons IO
- How to convert an InputStream to a File in Java
- You might also like.
How to Convert an InputStream to a File in Java
Let’s see how we many convert an InputStream to a File in Java.
1. InputStream::transferTo (Java 9)
In Java 9, we can copy bytes from an input stream to an output stream using InputStream::transferTo .
static void copyStreamToFile(InputStream in, File file) try (OutputStream out = new FileOutputStream(file)) in.transferTo(out); > catch (IOException e) e.printStackTrace(); > >
2. Files::copy (Java 7)
In Java 7, we can use Files::copy to copy bytes from an input stream to a file.
static void copyInputStreamToFile(InputStream in, File file) Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); >
3. IOUtils::copy (Apache Commons IO)
With commons-io we have access to IOUtils::copy , which will allow us to copy bytes from one stream to another (in this case, a FileOutputStream ).
static void copyStreamToFile(InputStream in, File file) try (OutputStream out = new FileOutputStream(file)) IOUtils.copy(in, out); > catch (FileNotFoundException e) e.printStackTrace(); > catch (IOException e) e.printStackTrace(); > >
4. FileUtils::copyInputStreamToFile (Apache Commons IO)
With commons-io , we also have access to FileUtils::copyInputStreamToFile to copy a source stream into a file destination.
static void copyStreamToFile(InputStream in, File file) FileUtils.copyInputStreamToFile(in, file); >
5. Plain Java (no external libraries)
If we decide to use plain Java, we can manually read the bytes from the input stream to some output stream.
static void copyStreamToFile(InputStream in, File file) OutputStream out = new FileOutputStream(file); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read); > out.close(); >
Java – Write an InputStream to a File
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.
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:
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:
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’ll illustrate how to write an InputStream to a File. First we’ll use plain Java, then Guava, and finally the Apache Commons IO library.
This article is part of the “Java – Back to Basic” tutorial here on Baeldung.
Further reading:
Java — InputStream to Reader
Java — Convert File to InputStream
How to open an InputStream from a Java File — using plain Java, Guava and the Apache Commons IO library.
Java InputStream to Byte Array and ByteBuffer
2. Convert Using Plain Java
Let’s start with the Java solution:
@Test public void whenConvertingToFile_thenCorrect() throws IOException < Path path = Paths.get("src/test/resources/sample.txt"); byte[] buffer = java.nio.file.Files.readAllBytes(path); File targetFile = new File("src/test/resources/targetFile.tmp"); OutputStream outStream = new FileOutputStream(targetFile); outStream.write(buffer); IOUtils.closeQuietly(outStream); >
Note that in this example, the input stream has known and pre-determined data, such as a file on disk or an in-memory stream. As a result, we don’t need to do any bounds checking and we can, if memory allows, simply read it and write it in one go.
If the input stream is linked to an ongoing stream of data, like an HTTP response coming from an ongoing connection, then reading the entire stream once isn’t an option. In that case, we need to make sure we keep reading until we reach the end of the stream:
@Test public void whenConvertingInProgressToFile_thenCorrect() throws IOException < InputStream initialStream = new FileInputStream( new File("src/main/resources/sample.txt")); File targetFile = new File("src/main/resources/targetFile.tmp"); OutputStream outStream = new FileOutputStream(targetFile); byte[] buffer = new byte[8 * 1024]; int bytesRead; while ((bytesRead = initialStream.read(buffer)) != -1) < outStream.write(buffer, 0, bytesRead); >IOUtils.closeQuietly(initialStream); IOUtils.closeQuietly(outStream); >
Finally, here’s another simple way we can use Java 8 to do the same operation:
@Test public void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException < InputStream initialStream = new FileInputStream( new File("src/main/resources/sample.txt")); File targetFile = new File("src/main/resources/targetFile.tmp"); java.nio.file.Files.copy( initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); IOUtils.closeQuietly(initialStream); >
3. Convert Using Guava
Next, let’s take a look at a simpler Guava based solution:
@Test public void whenConvertingInputStreamToFile_thenCorrect3() throws IOException < InputStream initialStream = new FileInputStream( new File("src/main/resources/sample.txt")); byte[] buffer = new byte[initialStream.available()]; initialStream.read(buffer); File targetFile = new File("src/main/resources/targetFile.tmp"); Files.write(buffer, targetFile); >
4. Convert Using Commons IO
Finally, here’s an even quicker solution with Apache Commons IO:
@Test public void whenConvertingInputStreamToFile_thenCorrect4() throws IOException < InputStream initialStream = FileUtils.openInputStream (new File("src/main/resources/sample.txt")); File targetFile = new File("src/main/resources/targetFile.tmp"); FileUtils.copyInputStreamToFile(initialStream, targetFile); >
And there we have it, 3 quick ways of writing the InputStream to a File.
The implementation of all these examples can be found in our GitHub project.
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:
How to convert an InputStream to a File in Java
In this quick article, you’ll learn how to convert an instance of InputStream to a file using Java. In Java, there are several ways to do this conversion as explained below.
In Java 7 or higher, you can use the Files.copy() method from Java’s NIO API to copy an InputStream object to a file as shown below:
try (InputStream stream = Files.newInputStream(Paths.get("input.txt"))) // convert stream to file Files.copy(stream, Paths.get("output.txt")); > catch (IOException ex) ex.printStackTrace(); >
The above code will throw an error if the file already exists. To replace the existing file, you can use the below example code:
try (InputStream stream = Files.newInputStream(Paths.get("input.txt"))) // convert stream to file Files.copy(stream, Paths.get("output.txt"), StandardCopyOption.REPLACE_EXISTING); > catch (IOException ex) ex.printStackTrace(); >
In Java 6 or below, you can use the OutputStream class to manually copy data from InputStream to a file as shown below:
try (InputStream inputStream = new FileInputStream(new File("input.txt")); OutputStream outputStream = new FileOutputStream(new File("output.txt"))) int length; byte[] bytes = new byte[1024]; // copy data from input stream to output stream while ((length = inputStream.read(bytes)) != -1) outputStream.write(bytes, 0, length); > > catch (IOException ex) ex.printStackTrace(); >
The Apache Commons IO library provides IOUtils.copyInputStreamToFile() method to easily copy an instance of InputStream to a file as shown below:
try (InputStream stream = Files.newInputStream(Paths.get("input.txt"))) // convert input stream to file FileUtils.copyInputStreamToFile(stream, new File("output.txt")); > catch (IOException ex) ex.printStackTrace(); >
dependency> groupId>commons-iogroupId> artifactId>commons-ioartifactId> version>2.6version> dependency>
implementation 'commons-io:commons-io:2.6'
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.