Java Program to write into a file using BYTE STREAM .
Objective
Write a Java program to write data into a file using Byte Streams.
Algorithm / Approach
- Import
java.io.*andjava.util.*. - Prompt the user for a filename and a string of data.
- Inside a
tryblock, initialize aFileOutputStreamwith the filename. - Convert the string data into a byte array using
data.getBytes(). - Write the byte array to the file using
fout.write(b). - In the
finallyblock, ensure the stream is closed usingfout.close().
WriteFile.java
import java.io.*;
import java.util.*;
class WriteFile {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter File Name: ");
String file = s.nextLine();
FileOutputStream fout = null;
try {
fout = new FileOutputStream(file);
System.out.print("Enter Data: ");
String data= s.nextLine();
byte[] b = data.getBytes();
fout.write(b);
System.out.print("Written successfully");
}
catch(IOException e){
System.out.print(e);
}
finally {
try{
fout.close();
}
catch(Exception e) {
System.out.print(e);
}
}
}
}
Expected Output
Enter File Name: Alok.txt Enter Data: Java Prowess is developed by Java, Android Trainer Written successfully
Explanation of the Program
- In Java, a Stream is a logical connection to a data source (like a file).
- Byte Streams (classes ending in
InputStreamorOutputStream) handle data 8 bits (1 byte) at a time. They are the most fundamental type of stream and are perfect for binary data like images or audio. - When writing text with a Byte Stream, you must manually convert your human-readable String into raw bytes before writing it to the file.
Complexity
Time Complexity
O(n) - Where n is the number of bytes written.
Space Complexity
O(n) - To hold the byte array in memory.