Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to write into a file using CHARACTER STREAM .

Java Code Example — File Handling Programs

ADVERTISEMENT

Java Program to write into a file using CHARACTER STREAM .

Objective

Write a Java program to write text into a file using Character Streams.

Algorithm / Approach

  1. Prompt the user for a filename and string data.
  2. Inside a try block, initialize a FileWriter.
  3. Directly pass the String to fw.write(data).
  4. Close the writer in the finally block.
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 fileName = s.nextLine();
  FileWriter fw = null;
  try {
   fw = new FileWriter(fileName);
   System.out.print("Enter Data: ");
   String data= s.nextLine();
   fw.write(data);
   System.out.println("Written successfully");
  }
  catch(IOException e){
   System.out.print(e);
  }
  finally {
   try {
    fw.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

  • Character Streams (classes ending in Reader or Writer) handle data 16 bits (2 bytes) at a time, specifically matching the size of a Java char (which uses UTF-16 Unicode).
  • Because they are designed specifically for text, they are much easier to use for writing strings. Notice that we didn't need to convert the String to a byte array—FileWriter handles the character encoding automatically.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT