Java Fileoutputstream Class

The Java FileOutputStream is a type of output stream that is utilized for the purpose of writing data to a file.

When you need to save primitive values to a file, the FileOutputStream class is the way to go. This class supports writing both byte-oriented and character-oriented data. However, when dealing specifically with character-oriented data, it's recommended to opt for FileWriter over FileOutputStream.

FileOutputStream class declaration

Let's examine the declaration of the Java.io.FileOutputStream class:

Example

public class FileOutputStream extends OutputStream

FileOutputStream class methods

Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to writeary.lengthbytes from the bytearrayto the file output stream.
void write(byte[] ary, int off, int len) It is used to writelenbytes from the byte array starting at offsetoffto the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte

Example

import java.io.FileOutputStream;

public class FileOutputStreamExample {

	public static void main(String args[]){  

		   try{  

		     FileOutputStream fout=new FileOutputStream("D:\\testout.txt");  

		     fout.write(65);  

		     fout.close();  

		     System.out.println("success...");  

		    }catch(Exception e){System.out.println(e);}  

	  }  

}

Output:

Output

Success...

The information stored in the file named testout.txt is configured with the value A.

testout.txt

Java FileOutputStream example 2: write string

Example

import java.io.FileOutputStream;

public class FileOutputStreamExample {

	public static void main(String args[]){  

		   try{  

		     FileOutputStream fout=new FileOutputStream("D:\\testout.txt");  

		     String s="Welcome to Java.";  

		     byte b[]=s.getBytes();//converting string into byte array  

		     fout.write(b);  

		     fout.close();  

		     System.out.println("success...");  

		    }catch(Exception e){System.out.println(e);}  

	  }  

}

Output:

Output

Success...

The data stored in the text file named testout.txt has been assigned the content "Welcome to Java".

testout.txt

Example

Welcome to Java.

Input Required

This code uses input(). Please provide values below: