Java FileInputStream and FileOutputStream Example

Using Java FileInputStream and FileOutputStream classes we can read data from a file and write data to a file respectively. In this post, we will see the example of writing data to a file and reading from a file.

FileOutputStream Example

Following is an example of how to write byte stream data in a file using a FileOutputStream:

import java.io.*;

public class FileOutputStreamDemo {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		FileOutputStream fos = new FileOutputStream("test.txt");
		String data = "Coder Sathi is writing data to file.";
		byte[] dataByteArray = data.getBytes();

		fos.write(dataByteArray);
	}
}

This code writes data to file test.txt.

FileInputStream Example

Following is an example of how to read byte stream data from a file using FileInputStream class:

import java.io.*;

public class FileInputStreamDemo {
    public static void main(String[] args) {
        FileInputStream fis = null;

        try {
            // Open the file "test.txt" for reading
            fis = new FileInputStream("test.txt");

            // Read bytes from the file and print them
            int byteRead;
            while ((byteRead = fis.read()) != -1) {
                System.out.print((char) byteRead); // Convert byte to char and print
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close(); // Close the FileInputStream in the finally block
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

The above example code reads the data from a file we’ve written in the FileOutputStream example.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments