FileOutputStream example code

Learn how to use FileOutputStream of Java to write into a file.

FileOutputStream example code

Learn how to use FileOutputStream of Java to write into a file.

FileOutputStream example code

Writing a file using FileOutputStream

    

Writing a file using FileOutputStream

As we discussed earlier, java has two kinds of streams- Byte & Characters. For reading and writing binary data, byte stream is incorporated. The OutputStream abstract class is used to write data to a file. The FileOutputStream is the subclass of the OutputStream  abstract class. The FileOutputStream  is used to write data to a file.

For writing data like bytes, integers, floats, or other "data" orientated types, we incorporate DataOutputStream while for text we should use PrintStream class.

Given below example will give you a clear idea how to use FileOutputStream :

Example

import java.io.*;

// Example of FileOutputStream
public class FileOutStreamDemo {
public static void main(String[] args) {
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try {
// Create a new file output stream
// connected to "DevFile.txt"
out = new FileOutputStream("DevFile.txt");

// Connect print stream to the output stream
p = new PrintStream(out);

p.println("The text shown here will write to a file after run");

System.out.println("The Text is written to DevFile.txt");

p.close();
} catch (Exception e) {
System.err.println("Error writing to file");
}
}

}

Output :

The following message will appear on command prompt :

 The Text is written to DevFile.txt   

The Content of the text file:

Download Source Code