FileOutputStream

java.io.FileOutputStream Example

In this example we are going to talk about FileOutputStream. FileOutputStream is a subclass of OutputStream, which is used to transfer data from your program to a resource. And in this case to a file that resides in your underlying file system.

OK, so let’s start with some simple examples.
 
 
 
 
 
 

1. Writing bytes to a file

Let’s see how you can obtain a FileOutputStream and write bytes to a file.

FileOutputStreamExample.java:

package com.javacodegeeks.core.io.outputstream;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamExample {

    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 (FileOutputStream 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 file resource using FileOutputStream:

  • void write(byte[] b). Write all the bytes of byte array b in the destination resource.
  • void write(byte[] b, int off, int len). Write a sub sequence of the byte array.
  • void write(int b). Write a single byte.

All these methods write a sequence of bytes in the destination file (or a single byte). If one of these methods returns successfully, then you are be able to read the bytes that you’ve written, from that 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 happen for performance reasons.

2. Buffering a FileOutputStream

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.

FileOutputStreamExample.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 FileOutputStreamExample {

    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 (BufferedOutputStream 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.

FileOutputStreamExample.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 FileOutputStreamExample {

    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();
        }
    }
}

3. Writing characters to a file

When dealing with binary files, writing bytes is enough. But very often you need to write text files form your program. In order to write directly characters to your output file, which now should be considered as a text file, you can wrap the FileOutputStream around an 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.

FileOutputStreamExample.java:

package com.javacodegeeks.core.io.outputstream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class FileOutputStreamExample {

    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:

FileOutputStreamExample.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 FileOutputStreamExample {

    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();
        }
    }
}

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.

FileOutputStreamExample.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 FileOutputStreamExample {

    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();
        }
    }
}

here is also a more convenient way to create a PrintWriter to a file, if you absolutely have to :

FileOutputStreamExample.java:

package com.javacodegeeks.core.io.outputstream;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;

public class FileOutputStreamExample {

    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();
        }
    }
}

I would prefer the former method as it uses buffering.

4. Obtain an OutputStream using NIO

You can use the Files NIO class to obtain an OutputStream to a file.

FileOutputStreamExample.java:

package com.javacodegeeks.core.io.outputstream;

import java.io.FileOutputStream;
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 FileOutputStreamExample {

    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.FileOutputStream Example. Download the code of this example here : FileOutputStreamExample.zip

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button