java.io.OutputStream Example
In this example we are going to talk about OutputStream
class in Java. OutputStream
is an abstract class that enables you to write data to an output sink or destination. As with InputStream
, that destination could be a console, a file, a socket, a pipe and even a buffer in memory. The most basic and fundamental thing you can do with an OutputStream
is write a sequence of bytes to it.
1. Simple OutputStream Examples
In this section we are going to see how you can use OutputStream
and it’s basic API methods to write bytes to a file. For this, Java offers a subclass of OutputStream
that can be connected to a file destination. This is a FileOutputStream
.
Let’s see how you can use it.
OutputStreamExample .java:
package com.javacodegeeks.core.io.outputstream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class OutputStreamExample { private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt"; public static void main(String[] args) { String content = "Hello Java Code Geeks"; byte[] bytes = content.getBytes(); try (OutputStream out = new FileOutputStream(OUTPUT_FILE)) { // write a byte sequence out.write(bytes); // write a single byte out.write(bytes[0]); // write sub sequence of the byte array out.write(bytes,4,10); } catch (IOException e) { e.printStackTrace(); } } }
These are the basic three API methods that can write bytes to a destination resource, in this case a file :
void write(byte[] b)
. Write all the bytes of byte array b in the destination resourcevoid write(byte[] b, int off, int len)
. Write a sub sequence of the byte arrayvoid write(int b)
. Write a single byte
All these methods write a sequence of bytes in the destination resource (or a single byte). If one of these methods return successfully, then you are be able to read the bytes that you’ve written, from that resource. In the case of that resource being a file, it is not guaranteed that the bytes will be persisted in the physical device at which your file system runs on. On the contrary, in most cases they will be written in a system buffer. It’s the operating system’s and the hardware’s responsibility when and how to write those bytes in the psychical device. Of course, all of these happens for performance reasons.
It is also worth noting that most classes that extend OutputStream
, provide their own, efficient implementation of the aforementioned OutpuStream
‘s fundamental methods.
1. Buffering an OutputStream
When you develop a very I/O intensive application that need to write large sequence of bytes in large files, then it’s highly advised that you should use some buffering. The basic idea of buffering is that you will use an internal,intermediate buffer to append your bytes. This means that the system won’t have to call the underlying OS’s “write
” method for every single byte, but instead operate in this sequence of byte. This can make a big difference in performance sensitive applications, as is reduces the amount of expensive I/O operations.
To do this, Java offers a wrapper class, BufferedOutputStream
. Let’s see how you can use it.
OutputStreamExample .java:
package com.javacodegeeks.core.io.outputstream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class OutputStreamExample { private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt"; public static void main(String[] args) { String content = "Hello Java Code Geeks"; byte[] bytes = content.getBytes(); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(OUTPUT_FILE),1024)) { // write a byte sequence out.write(bytes); // write a single byte out.write(bytes[0]); // write sub sequence of the byte array out.write(bytes,4,10); } catch (IOException e) { e.printStackTrace(); } } }
As you can see there’s not much that is different. Notice that I can choose the size of the aforementioned internal buffer, in this case 1024 bytes. If you don’t provide that second argument to the BufferedOutputStream
constructor, the default buffer of 512 bytes will be used (which is sufficient in most cases).
OutputStream
also offers a flush()
method. What this does is to force any buffered output bytes to be written out to the target resource. In our case that resource is a file. Again when those buffered bytes are flushed, ti does not necessarily mean that they will be written in the physical disk.
OutputStreamExample .java:
package com.javacodegeeks.core.io.outputstream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class OutputStreamExample { private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt"; public static void main(String[] args) { String content = "Hello Java Code Geeks"; byte[] bytes = content.getBytes(); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(OUTPUT_FILE),1024)) { // write a byte sequence out.write(bytes); // write a single byte out.write(bytes[0]); // write sub sequence of the byte array out.write(bytes,4,10); // flush the outputstream out.flush(); } catch (IOException e) { e.printStackTrace(); } } }
2. Writing characters
Java also offers some convenient classes that bridge an byte stream to a character stream. In the case of OutputStream
this class is OutputStreamWriter
. Using this, you can directly write characters or Strings
without having to obtain a byte array out of them. You can also specify the character set that you want your characters to be encoded to, or else the default will be used.
OutputStreamExample .java:
package com.javacodegeeks.core.io.outputstream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class OutputStreamExample { private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt"; public static void main(String[] args) { String content = "Hello Java Code Geeks"; char[] chars = content.toCharArray(); try (OutputStreamWriter outWriter = new OutputStreamWriter(new FileOutputStream(OUTPUT_FILE),"utf-8")) { // write the whole string outWriter.write(content); // write a substring of the original string outWriter.write(content,5,11); // write a character sequence outWriter.write(chars); // write a single character outWriter.write(chars[0]); // write sub sequence of the character array outWriter.write(chars,4,10); } catch (IOException e) { e.printStackTrace(); } } }
And of course there is a buffered version of OutputStreamWriter
, named BufferedWriter
. Let’s see how you can use it:
OutputStreamExample .java:
package com.javacodegeeks.core.io.outputstream; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class OutputStreamExample { private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt"; public static void main(String[] args) { String content = "Hello Java Code Geeks"; char[] chars = content.toCharArray(); try (BufferedWriter outWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(OUTPUT_FILE),"utf-8"),1024)) { // write the whole string outWriter.write(content); // change line outWriter.newLine(); // write a substring of the original string outWriter.write(content,5,11); outWriter.newLine(); // write a character sequence outWriter.write(chars); outWriter.newLine(); // write a single character outWriter.write(chars[0]); outWriter.newLine(); // write sub sequence of the character array outWriter.write(chars, 4, 10); } catch (IOException e) { e.printStackTrace(); } } }
Besides buffering, which is the main reason why you should use BufferedWriter
, it offers a newLine()
methods, that uses the platform’s new line character in order to append it to your output. This will enable you to change line when writing in text files. Of course flush()
method is also available here.
Another convenient class when working with character streams is PrintWriter
class. It offers several methods like println
, print
and printf
to customize the character stream output the way you want.
OutputStreamExample .java:
package com.javacodegeeks.core.io.outputstream; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class OutputStreamExample { private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt"; public static void main(String[] args) { String content = "Hello Java Code Geeks"; char[] chars = content.toCharArray(); try (PrintWriter outWriter = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(OUTPUT_FILE))))) { // Write the string outWriter.print(content); // Write the string and change line outWriter.println(content); // Format the output outWriter.printf("%s\n",content); } catch (IOException e) { e.printStackTrace(); } } }
There is also a more convenient way to create a PrintWriter
to a file, if you absolutely have to :
OutputStreamExample .java:
package com.javacodegeeks.core.io.outputstream; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter;; public class OutputStreamExample { private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt"; public static void main(String[] args) { String content = "Hello Java Code Geeks"; char[] chars = content.toCharArray(); try (PrintWriter outWriter = new PrintWriter( new PrintStream(OUTPUT_FILE))) { // Write the string outWriter.print(content); // Write the string and change line outWriter.println(content); // Format the output outWriter.printf("%s\n", content); } catch (IOException e) { e.printStackTrace(); } } }
2. Writing to memory buffers
You can use a ByteArrayOutputStream
to write raw bytes an an in memory byte array.
OutputStreamExample .java:
package com.javacodegeeks.core.io.outputstream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; public class OutputStreamExample { private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt"; public static void main(String[] args) { String content = "Hello Java Code Geeks"; byte[] bytes = content.getBytes(); char[] chars = content.toCharArray(); try (ByteArrayOutputStream out= new ByteArrayOutputStream()) { out.write(bytes); System.out.println(Arrays.toString(out.toByteArray())); System.out.println(out.toString()); // Write the internal buffer to an output stream out.writeTo(new FileOutputStream(OUTPUT_FILE)); } catch (IOException e) { e.printStackTrace(); } } }
This will output :
[72, 101, 108, 108, 111, 32, 74, 97, 118, 97, 32, 67, 111, 100, 101, 32, 71, 101, 101, 107, 115]
Hello Java Code Geeks
2. Obtain an OutputStream using NIO
You can use the Files
NIO class to obtain an OutputStream
to a file.
OutputStreamExample .java:
package com.javacodegeeks.core.io.outputstream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class OutputStreamExample { private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt"; public static void main(String[] args) { String content = "Hello Java Code Geeks"; byte[] bytes = content.getBytes(); Path filepath = Paths.get(OUTPUT_FILE); try ( OutputStream out = Files.newOutputStream(filepath)) { out.write(bytes); } catch (IOException e) { e.printStackTrace(); } } }
Download source code
This was a java.io.OutputStream Example. You can download the source code of this example here : OutputStreamExample.zip