Java I/O How to - Create a file output stream directly from the file name








Question

We would like to know how to create a file output stream directly from the file name.

Answer

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/*w  ww  .  ja v  a 2 s . c o  m*/
public class Main {
  public static void main(String[] a) {
    FileOutputStream outputFile = null; // Place to store the stream reference
    try {
      outputFile = new FileOutputStream("myFile.txt");
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
  }
}




Answer 2

Create FileOutputStream object from File object

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

public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("C:/demo.txt");
    FileOutputStream fos = new FileOutputStream(file);
  }
}