Java FileOutputStream Example

This example discuss about the FileOutputStream. This class extends from the OutputStream and used for writing the stream of bytes into a file. This class has the following constructors for creating the instance.

  • FileOutputStream(File file) – Creates a file output stream to write to the file represented by the specified File object.
  • FileOutputStream(File file, boolean append) – Creates a file output stream to write to the file represented by the specified File object.
  • FileOutputStream(FileDescriptor fdObj) – Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.
  • FileOutputStream(String name) – Creates a file output stream to write to the file with the specified name.
  • FileOutputStream(String name, boolean append) – Creates a file output stream to write to the file with the specified name.

Also this class has the following overloaded methods for writing the streams to a file.

  • 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.

Lets look at the simple example on how to use FileOutputStream for writing to a file.

package javabeat.net.core;

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

/**
 * Java FileOutputStream Example
 *
 * @author Krishna
 *
 */
public class FileOutputStreamExample {
	public static void main (String args[]) throws IOException{
		//Creating file instance
		File file = new File("TextFile.txt");

		//Creating file output stream instance
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		String str = "This is example for FileOutputStream";

		//Gets byte array
		byte b[] = str.getBytes();

		//Writing byte array to a file
		fileOutputStream.write(b);

		//Closing the stream
		fileOutputStream.close();
	}
}

If you run the above program, the file named “TextFile.txt” will be created in the same director with the given content.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!