Programming Tutorials

FileOutputStream - sample program in Java

By: Abinaya in Java Tutorials on 2007-09-14  

FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most commonly used constructors are shown here:

FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)

They can throw an IOException or a SecurityException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. If append is true, the file is opened in append mode. Creation of a FileOutputStream is not dependent on the file already existing. FileOutputStream will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an IOException will be thrown.

The following example creates a sample buffer of bytes by first making a String and then using the getBytes() method to extract the byte array equivalent. It then creates three files. The first, file1.txt, will contain every other byte from the sample. The second, file2.txt, will contain the entire set of bytes. The third and last, file3.txt, will contain only the last quarter. Unlike the FileInputStream methods, all of the FileOutputStream methods have a return type of void. In the case of an error, these methods will throw an IOException.

// Demonstrate FileOutputStream.

class FileOutputStreamDemo {
    public static void main(String args[]) throws Exception {
        String source = "Now is the time for all good men\\n"
                + " to come to the aid of their country\\n"
                + " and pay their due taxes.";
        byte buf[] = source.getBytes();
        OutputStream f0 = new FileOutputStream("file1.txt");
        for (int i = 0; i < buf.length; i += 2) {
        OutputStream f1 = new FileOutputStream("file2.txt");
        OutputStream f2 = new FileOutputStream("file3.txt");
        f2.write(buf, buf.length - buf.length / 4, buf.length / 4);

When you run this code, three files will be created in the current directory. Here are the contents of each file after running this program.

First, file1.txt:
Nwi h iefralgo e
t oet h i ftercuty n a hi u ae.
Next, file2.txt:
Now is the time for all good men
to come to the aid of their country
and pay their due taxes.
Finally, file3.txt: and pay their due taxes.

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)