Java FileOutputStream class

Introduction

Java FileOutputStream extends an OutputStream to write bytes to a file.

It implements the AutoCloseable , Closeable, and Flushable interfaces.

Four of its constructors are shown here:

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

Full source


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

public class Main {
  public static void main(String args[]) {
    String source = "demo from demo2s.com";
    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]);/*from  ww  w . j a v  a2s . c  om*/

      // 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 Occured");
    }
  }
}



PreviousNext

Related