Write file with inputstream in java

File Handling in Java

In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file.

Why File Handling is Required?

  • File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it.
  • In simple words, file handling means reading and writing data to a file.

Java

In Java, the concept Stream is used in order to perform I/O operations on a file. So at first, let us get acquainted with a concept known as Stream in Java.

Streams in Java

  • In Java, a sequence of data is known as a stream.
  • This concept is used to perform I/O operations on a file.
  • There are two types of streams :

1. Input Stream:

The Java InputStream class is the superclass of all input streams. The input stream is used to read data from numerous input devices like the keyboard, network, etc. InputStream is an abstract class, and because of this, it is not useful by itself. However, its subclasses are used to read data.

Читайте также:  Rock paper scissors lizard spock python

There are several subclasses of the InputStream class, which are as follows:

  1. AudioInputStream
  2. ByteArrayInputStream
  3. FileInputStream
  4. FilterInputStream
  5. StringBufferInputStream
  6. ObjectInputStream

Creating an InputStream

// Creating an InputStream InputStream obj = new FileInputStream();

Here, an input stream is created using FileInputStream.

Note: We can create an input stream from other subclasses as well as InputStream.

Methods of InputStream

S No. Method Description
1 read() Reads one byte of data from the input stream.
2 read(byte[] array)() Reads byte from the stream and stores that byte in the specified array.
3 mark() It marks the position in the input stream until the data has been read.
4 available() Returns the number of bytes available in the input stream.
5 markSupported() It checks if the mark() method and the reset() method is supported in the stream.
6 reset() Returns the control to the point where the mark was set inside the stream.
7 skips() Skips and removes a particular number of bytes from the input stream.
8 close() Closes the input stream.

2. Output Stream:

The output stream is used to write data to numerous output devices like the monitor, file, etc. OutputStream is an abstract superclass that represents an output stream. OutputStream is an abstract class and because of this, it is not useful by itself. However, its subclasses are used to write data.

There are several subclasses of the OutputStream class which are as follows:

  1. ByteArrayOutputStream
  2. FileOutputStream
  3. StringBufferOutputStream
  4. ObjectOutputStream
  5. DataOutputStream
  6. PrintStream

Creating an OutputStream

// Creating an OutputStream OutputStream obj = new FileOutputStream();

Here, an output stream is created using FileOutputStream.

Note: We can create an output stream from other subclasses as well as OutputStream.

Methods of OutputStream

S. No. Method Description
1. write() Writes the specified byte to the output stream.
2. write(byte[] array) Writes the bytes which are inside a specific array to the output stream.
3. close() Closes the output stream.
4. flush() Forces to write all the data present in an output stream to the destination.

Based on the data type, there are two types of streams :

1. Byte Stream:

This stream is used to read or write byte data. The byte stream is again subdivided into two types which are as follows:

  • Byte Input Stream: Used to read byte data from different devices.
  • Byte Output Stream: Used to write byte data to different devices.

2. Character Stream:

This stream is used to read or write character data. Character stream is again subdivided into 2 types which are as follows:

  • Character Input Stream: Used to read character data from different devices.
  • Character Output Stream: Used to write character data to different devices.

Owing to the fact that you know what a stream is, let’s polish up File Handling in Java by further understanding the various methods that are useful for performing operations on the files like creating, reading, and writing files.

Java File Class Methods

The following table depicts several File Class methods:

Method Name Description Return Type
canRead() It tests whether the file is readable or not. Boolean
canWrite() It tests whether the file is writable or not. Boolean
createNewFile() It creates an empty file. Boolean
delete() It deletes a file. Boolean
exists() It tests whether the file exists or not. Boolean
length() Returns the size of the file in bytes. Long
getName() Returns the name of the file. String
list() Returns an array of the files in the directory. String[]
mkdir() Creates a new directory. Boolean
getAbsolutePath() Returns the absolute pathname of the file. String

Let us now get acquainted with the various file operations in Java.

File operations in Java

The following are the several operations that can be performed on a file in Java :

Now let us study each of the above operations in detail.

1. Create a File

  • In order to create a file in Java, you can use the createNewFile() method.
  • If the file is successfully created, it will return a Boolean value true and false if the file already exists.

Following is a demonstration of how to create a file in Java :

Источник

Write an InputStream to a File in Java

In this tutorial, we are going to learn how to write InputStream to a File in Java. We will use plain Java and libraries with utility classes to process IO operations like Guava and Apache Common IO .

For more Java I/O related articles, check the following links:

2. InputStream to a File using FileOutputStream

Let’s start with a plain Java solution. Java provides FileOutputStream class that can be used to write an InputStream to a File :

package com.frontbackend.java.io.conversions; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class InputStreamToFileUsingFileOutputStream < public static void main(String[] args) throws IOException < byte[] bytes = < 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 >; // frontbackend InputStream inputStream = new ByteArrayInputStream(bytes); File file = new File("/tmp/output.txt"); try (FileOutputStream outputStream = new FileOutputStream(file)) < int read; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) < outputStream.write(bytes, 0, read); >> > > 

In this example, first, we created ByteArrayInputStream filled with sample bytes. Then, in a loop, we read bytes from that InputStream and write them into the FileOutputStream . Bytes are saved in the /tmp/output.txt file using FileOutputStream.write method. In this snippet, we used try-with-resources expression to automatically close OutputStream after IO operations.

3. Write InputStream to File using Files from Java NIO

Java new IO API comes with many utility classes and methods which do a lot of work under the hood. In the following example, we used Files.copy method which is specially designed for processing file streams:

package com.frontbackend.java.io.conversions; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class InputStreamToFileUsingFiles < public static void main(String[] args) throws IOException < byte[] bytes = < 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 >; // frontbackend InputStream inputStream = new ByteArrayInputStream(bytes); File file = new File("/tmp/output.txt"); Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING); > > 

Files.copy method copies all bytes from an input stream to a file. We just need to fill three arguments of that utility method:

  • the first argument is the input stream to read from,
  • the second parameter is the path to the file,
  • the third parameter contains options specifying how the copy should be done.

In our example, the third argument is set to StandardCopyOption.REPLACE_EXISTING — if the target file exists it will be replaced with the new content.

4. InputStream to File using Guava library

Another way to write InputStream to a File in Java is to use an external library like Guava . The Guava comes with many utility classes dedicated to IO operations. In the following example, we used ByteStreams.copy(inputStream, outputStream) method that simply copy InputStream to the OutputStream (in our case FileOutputStream is our output stream):

package com.frontbackend.java.io.conversions; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import com.google.common.io.ByteStreams; public class InputStreamToFileUsingGuava < public static void main(String[] args) throws IOException < byte[] bytes = < 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 >; // frontbackend InputStream inputStream = new ByteArrayInputStream(bytes); File file = new File("/tmp/output.txt"); try (FileOutputStream outputStream = new FileOutputStream(file)) < ByteStreams.copy(inputStream, outputStream); >> > 

Note that ByteStreams.copy operation did not close the streams so we have to do it explicitly.

To start using Guava you have to include a special dependency on your project or download a JAR file. The latest version of Guava library is available under the following links:

5. Convert InputStream to File using Apache Commons IO library

Apache Commons IO is another library we can use to write InputStream to a File in Java. That tool provides the dedicated method that writes an InputStream to the File directly — FileUtils.copyInputStreamToFile(inputStream, file) .

This allows us to create a single-line solution:

package com.frontbackend.java.io.conversions; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.FileUtils; public class InputStreamToFileUsingFileUtils < public static void main(String[] args) throws IOException < byte[] bytes = < 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 >; // frontbackend InputStream inputStream = new ByteArrayInputStream(bytes); File file = new File("/tmp/output.txt"); FileUtils.copyInputStreamToFile(inputStream, file); > > 

The latest version of the Apache Commons IO library could be found under the following link: Maven Apache Commons IO 2.6

6. Conclusion

In this article, we presented several ways to write an InputStream to a File using libraries and plain Java. It is really up to you what solution you will choose.

Example snippets used in this tutorial are available under GitHub repository.

Источник

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