Creating Files Using FileOutputStream

Creating Files Using FileOutputStream

You accomplish basic file I/O in Java using data streams. The most basic file I/O operations in Java use the functionality offered by these classes:


If you’re new to Java, you’d probably assume that creating a file on the file system would be an operation on Java’s File class. Constructing a File class does not create a file on the system. However, the mkdir() method on the File class may be used to create a directory as follows:

 File dir = new File("mydir");dir.mkdir();

This code will create the directory “mydir” in the current working directory. Similarly, you can delete a file or a directory by invoking the delete() operation on an instance of the File class.

However, how do you create a file? The simplest way to create a file in Java is by opening an instance of a FileOutputStream. You can accomplish this by invoking one of the following FileOutputStream constructors:

 public FileOutputStream (String name)public FileOutputStream (File file) 

For example, you would create a file called “myfile” in the current working directory by calling one of the following:

 FileOutputStream fos = new  FileOutputStream("myfile");FileOutputStream fos = new FileOutputStream(new File("myfile"));


Share the Post: