Java FileOutputStream Example

FileOutputStream creates an OutputStream that you can use to write bytes to a file.

FileOutputStream Class Example

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

/**
 * The class demonstrate the usage of FileOutputStream class methods.
 * @author javaguides.net
 *
 */
public class FileOutputStreamDemo {
    public static void main(String args[]) {
         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();
         // Use try-with-resources to close the files.
         try (FileOutputStream f0 = new FileOutputStream("file1.txt");
              FileOutputStream f1 = new FileOutputStream("file2.txt");
              FileOutputStream f2 = new FileOutputStream("file3.txt")) {
              // write to first file
              for (int i = 0; i < buf.length; i += 2)
              f0.write(buf[i]);
              // write to second file
              f1.write(buf);
              // write to third file
              f2.write(buf, buf.length - buf.length / 4, buf.length / 4);
         } catch (IOException e) {
              System.out.println("An I/O Error Occurred");
     }
 }
}

Reference


Comments