Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to write into a file using BYTE STREAM .

Java Code Example — File Handling Programs

ADVERTISEMENT

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

  1. Import java.io.* and java.util.*.
  2. Prompt the user for a filename and a string of data.
  3. Inside a try block, initialize a FileOutputStream with the filename.
  4. Convert the string data into a byte array using data.getBytes().
  5. Write the byte array to the file using fout.write(b).
  6. In the finally block, ensure the stream is closed using fout.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 InputStream or OutputStream) 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.
ADVERTISEMENT